读取损坏的Excel使用C#

我想打开并使用C#控制台应用程序从损坏的Excel中读取数据。我试着用这个代码:

public System.Data.DataTable EXc(string path, string savedFile) { try { Missing missing = Missing.Value; Excel.Application excel = new Excel.Application(); Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Open(path, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlCorruptLoad.xlRepairFile); workbook.Close(true, missing, missing); if (workbook != null) { workbook.SaveAs(savedFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); } 

但我得到的例外

指定的投射无效

一致

 workbook.SaveAs(savedFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); 

你能帮我吗?

我承认我的错误:

我试图保存一个封闭的工作簿,可能是因为我得到了这个例外

指定的转换无效

使用interop打开损坏的excel后,我们可以使用oledb连接并将该数据复制到数据表或数据集中,并可以使用。

公共System.Data.DataTable CorruptedExcel(stringpath,stringsavedFile){

  try { Missing missing = Missing.Value; Excel.Application excel = new Excel.Application(); Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Open(path, CorruptLoad: Microsoft.Office.Interop.Excel.XlCorruptLoad.xlRepairFile); var connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=YES;TypeGuessRows=0;ImportMixedTypes=Text\""; //var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\""; ; using (var conn = new OleDbConnection(connectionString)) { conn.Open(); var sheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); using (var cmd = conn.CreateCommand()) { cmd.CommandText = "SELECT * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "] "; var adapter = new OleDbDataAdapter(cmd); adapter.Fill(dt); } } return dt; } catch (Exception e) { throw new Exception("ReadingExcel: Excel file could not be read! Check filepath.\n" + e.Message + e.StackTrace); } }