Error while opening excel in 2007
I have a C# WPF application which uses Excel interop libraries to generate and open excel sheets. This works fine till now on an XP machine with Office 2003. But I have recently migrated this to windows 2007 machine which has Excel 2007 running on it. Now my excel exports does't work anymore. It throws an error like the below:
System.Runtime.InteropServices.COMException (0x800A03EC): The document is corrupt and cannot be opened. To try and repair it, use the Open and Repair command in the Open dialog box and select Extract Data when prompted.
at Microsoft.Office.Interop.Excel.Workbooks.Open(String Filename, Object UpdateLinks, Object ReadOnly, Object Format, Object Password, Object WriteResPassword, Object IgnoreReadOnlyRecommended, Object Origin, Object Delimiter, Object Editable, Object Notify, Object Converter, Object AddToMru, 开发者_如何学JAVAObject Local, Object CorruptLoad)
I use the code below to open my excel file..
private void OpenSavedData(string fileName)
{
var excelApp = new Application();
excelApp.Workbooks.Open(
fileName,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
excelApp.Visible = true;
Marshal.ReleaseComObject(excelApp);
}
This has no trouble working in Office 2003 and XP, but for some reason fails on Win7 & Office 2007. Please can you let me know of any possible workarounds/solutions for this?
Thanks, -Mike
I think you may be using early binding with excel 2003 and this is why it doesnt work with excel 2007. Basically what you need to do is recompile your application while referencing the proper interop libraries for excel 2007 (Microsoft.Interop.Office.Excel version 1.6, can be found in "Add reference"->"COM" on a computer with Office 2007 installed). You can google early and late binding to get more information about it. Here is a link to get you started: http://peltiertech.com/Excel/EarlyLateBinding.html
I saw the same problem myself, when I upgrade to Windows 7. Perhaps it's the sudden shock to my WPF code of running in a 64-bit environment... I'm not sure !
My solution was a little drastic. I rewrote my WPF app's "Export to Excel" code completely, to use the OpenXML libraries, rather than using the VSTO libraries (which have always added a level of instability to my .Net apps).
I've documented what I've done, and all source code, plus a demo, is provided here: http://www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm
Once you've linked in my library, exporting a DataSet or DataTable is as simple as adding one line of code.
CreateExcelFile.CreateExcelDocument(myDataSet, "C:\\MikesExcelFile.xlsx");
It doesn't get much simpler than that !
Hope this helps.
Mike
精彩评论