【发布时间】:2011-07-13 23:28:11
【问题描述】:
我有一个通过在 Windows 资源管理器中双击打开的 Excel 工作簿,但无法在代码中访问它
Excel.Application xlApp = (Application)Marshal.GetActiveObject("Excel.Application");
Excel.Workbooks xlBooks = xlApp.Workbooks;
xlBooks.Count 等于 0,为什么不引用我打开的工作簿?
编辑
以下是各种场景和正在发生的事情:
场景 1:如果文件尚未打开
- 代码打开工作簿,我很高兴。
场景 2:如果文件最初是通过代码打开的,我关闭并重新打开应用程序
- 代码引用文件就好了
xlBooks.Count等于1,我很高兴。
场景 3:如果文件最初不是通过代码打开的,而是通过在资源管理器中双击来打开的
- 代码打开文件的另一个实例
xlBooks.Count等于0,我很生气!
这是现在的整个代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;
public class ExcelService : IExcelService
{
const string _filePath = @"C:\Somewhere";
const string _fileName = @"TestFile.xlsb";
string _fileNameAndPath = Path.Combine(_filePath, _fileName);
Application xlApp;
Workbooks xlBooks;
Workbook xlBook;
Worksheet xlSheet;
public ExcelService()
{
try
{
xlApp = (Application)Marshal.GetActiveObject("Excel.Application");
xlBooks = xlApp.Workbooks;
var numBooks = xlBooks.Count;
Log.Info("Number of workbooks: {0}".FormatWith(numBooks));
if (numBooks > 0)
{
xlBook = xlBooks[1];
Log.Info("Using already opened workbook");
}
else
{
xlBook = xlBooks.Open(_fileNameAndPath);
Log.Info("Opening workbook: {0}".FormatWith(_fileNameAndPath));
}
xlSheet = (Worksheet)xlBook.Worksheets[1];
// test reading a named range
string value = xlSheet.Range["TEST"].Value.ToString();
Log.Info(@"TEST: {0}".FormatWith(value));
xlApp.Visible = true;
}
catch (Exception e)
{
Log.Error(e.Message);
}
}
~ExcelService()
{
GC.Collect();
GC.WaitForPendingFinalizers();
try
{
Marshal.FinalReleaseComObject(xlSheet);
}
catch { }
try
{
Marshal.FinalReleaseComObject(xlBook);
}
catch { }
try
{
Marshal.FinalReleaseComObject(xlBooks);
}
catch { }
try
{
Marshal.FinalReleaseComObject(xlApp);
}
catch { }
}
}
【问题讨论】:
-
您确定您的 Excel 实例不超过一个?
-
向我们展示您尝试打开“已打开”电子表格的代码行。
-
骗了他自己的问题...哇...
-
是的,我很确定,我正在查看多个实例的任务管理器,并且只有一个我目前打开的实例。我也在析构函数中执行
Marshal.FinalReleaseComObject(xlApp);跨度>
标签: c# excel ms-office office-interop excel-interop