可否换一个思路,用组件的方式GetObject(, "Excel.Application") '判断Excel是否打开,返回结果?
直接用下面的代码 就能取出打开的EXCEL在进程中所有的文件了,包含能取到的路径和内容,
只要取到 Microsoft.Office.Interop.Excel.Application a = o as Microsoft.Office.Interop.Excel.Application; 这个对像,你就能为所欲为了,怎么操作EXCEL都成。剩下的就是你要去了解这个对像的操作EXCEL的方式。
[DllImport("ole32.dll")]
public static extern int GetRunningObjectTable(int reserved, out IRunningObjectTable prot);
[DllImport("ole32.dll")]
public static extern int CreateBindCtx(int reserved, out IBindCtx ppbc);
private Hashtable GetRunningObjectTable()
{
Hashtable result = new Hashtable();
IntPtr numFetched = IntPtr.Zero;
IRunningObjectTable runningObjectTable;
IEnumMoniker monikerEnumerator;
IMoniker[] monikers = new IMoniker[1];
GetRunningObjectTable(0, out runningObjectTable);
runningObjectTable.EnumRunning(out monikerEnumerator);
monikerEnumerator.Reset();
while (monikerEnumerator.Next(1, monikers, numFetched) == 0)
{
IBindCtx ctx;
CreateBindCtx(0, out ctx);
string runningObjectName;monikers[0].GetDisplayName(ctx, null, out runningObjectName);
object runningObjectVal;
runningObjectTable.GetObject(monikers[0], outrunningObjectVal);
result[runningObjectName] = runningObjectVal;
}
return result;
}
private bool XlsIsOpen(string fileName)
{
bool XlsIsOpen = false;
Hashtable rot = GetRunningObjectTable();
bool isOk = false;
foreach (object o in rot.Values)
{
if (isOk)
{
break;
}
Microsoft.Office.Interop.Excel.Application a = o as Microsoft.Office.Interop.Excel.Application;
if (a != null)
{
Microsoft.Office.Interop.Excel.Workbooks wbooks = a.Workbooks;
foreach (Microsoft.Office.Interop.Excel.Workbook wb in wbooks)
{
if (wb.Name == fileName)
{
Microsoft.Office.Interop.Excel.Worksheet sheet = wb.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;
int iRowCount = sheet.UsedRange.Rows.Count;
int iColCount = sheet.UsedRange.Columns.Count;
Microsoft.Office.Interop.Excel.Range range;
for (int iRow = 1; iRow <= iRowCount; iRow++)
{
for (int iCol = 1; iCol <= iColCount; iCol++)
{
Microsoft.Office.Interop.Excel.Range ss = (Microsoft.Office.Interop.Excel.Range)sheet.Cells[iRow, iCol];
Console.WriteLine(ss.Text);
}
}
XlsIsOpen = true;
isOk = true;
break;
}
}
//a.DisplayAlerts = false;
//a.Quit();
}
}
return XlsIsOpen;
}
private void Form1_Load(object sender, EventArgs e)
{
XlsIsOpen(@"XX.xls");
}
http://www.myexception.cn/c-sharp/1838673.html
自己在这个页面找到答案 自己修改了 里面代码在2010里有错误 需要修改