简体   繁体   中英

Opening Excel file in C# closing erroring

I'm opening an Excel file in .NET 4.0 (C#). I'm using the 12.0 version of interop. The Excel file is an xls (old). I can open it just fine, but workbook.close() causes a COM Exception with no real details around it.

oExcel = new Application();
oExcel.Visible = true;
oExcel.DisplayAlerts = false;

oBooks = oExcel.Workbooks;
oBook = null;
oBook = oBooks.Open(finalFilename);

oBook.Close();   // this gives COM Exception

Any ideas what I'm doing wrong?

Here is the interesting thing. I don't have to save this. After it does what it needs to do, I pull the data I need out and store it and the workbook I just made a copy of can just go away.

        Excel.Application objExcel = new Excel.Application();
        Excel.Workbook objWorkbook = (Excel.Workbook)(objExcel.Workbooks._Open(@"D:\a.xls", true,
        false, Missing.Value, Missing.Value, Missing.Value,
        Missing.Value, Missing.Value, Missing.Value,
        Missing.Value, Missing.Value, Missing.Value,
        Missing.Value));

your code...

            objWorkbook.Save();         
            objWorkbook.Close(true, @"C:\Documents and Settings\Administrator\b.xls", true);
            objExcel.Quit();

In my experience, errors on just opening and closing most likely indicates an issue with the file. Excel desktop is pretty forgiving and will gracefully handle any problem with the file. The file may look and work fine in Excel without giving any indication that something is wrong.

You could try re-saving the file in Excel. If it still doesn't work, try creating a fresh spreadsheet and copying the contents from the old file.

Workbook.Close does not appear to contain a method Close without parameters.

http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.close.aspx

Method Signature: void Close( Object SaveChanges, Object Filename, Object RouteWorkbook )

        object missing = Type.Missing;
        object noSave = false;
        oBook.Close(noSave, missing, missing);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM