关于操作Excel的奇怪问题
用C#操作Excel 开发环境是vs2005 导入了Interop.Excel.dll等引用
下面是代码
public string ExcelReplace(string filePath, string strOld, string strNew)
{
string strResult = "aaaaaa";
Application excel;
excel = new ApplicationClass();
excel.Visible = false;
string modelFile = filePath; //文件名
_Workbook wb = excel.Workbooks._Open(modelFile, Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
_Worksheet xSheet = (_Worksheet)wb.Sheets[1];
int icount = wb.Sheets.Count;
for (int i = 1; i <= icount; i++)
{
//try
//{
xSheet = (_Worksheet)wb.Sheets;
object what = strOld; //查找字符串
object retxt = strNew; //替换字符串
xSheet.Cells.Replace(what, retxt, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
//}
//catch
//{
// strResult = "trycuowu";
//}
}
wb.Save();
NAR(xSheet);
wb.Close(false, Missing.Value, Missing.Value);
NAR(wb);
excel.Quit();
NAR(excel);
System.GC.Collect();
return strResult;
}
private void NAR(object o)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(o);//强制释放一个对象
}
catch
{
}
finally
{
o = null;
}
}
报错
无法将类型为“System.__ComObject”的 COM 对象强制转换为接口类型“Excel._Worksheet”。此操作失败的原因是对 IID 为“{000208D8-0000-0000-C000-000000000046}”的接口的 COM 组件调用 QueryInterface 因以下错误而失败: 不支持此接口 (异常来自 HRESULT:0x80004002 (E_NOINTERFACE))。
高手求助