2017-04-26 181 views
0

我試圖的數據網格導出到Excel的文件,但我不斷收到此錯誤:如何糾正'System.Runtime.InteropServices.COMException'的這個錯誤?

An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in Test.exe 
Additional information: Ancien format ou bibliothèque de types non valide. 

這裏是我的代碼:

Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application(); //this generates the error 
     Workbook wb = Excel.Workbooks.Add(XlSheetType.xlWorksheet); 
     Worksheet ws = (Worksheet)Excel.ActiveSheet; 
     Excel.Visible = true; 
     ws.Cells[1, 1] = "Column1"; 
     ws.Cells[1, 2] = "Column2"; 
     ws.Cells[1, 3] = "Column3"; 
     ws.Cells[1, 4] = "Column4"; 
     ws.Cells[1, 5] = "Column5"; 
     for (int j=2; j <= dataGridView1.Rows.Count; j++) 
     { 
      for(int i= 2; i <= 5; i++) 
      { 
       ws.Cells[j, i] = dataGridView1.Rows[j-2].Cells[i-1].Value; 

      } 
     } 

如何糾正呢?

---------------------------編輯------------------ -----------------

我嘗試添加此:

System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US"); 

和它的工作,好像這個問題是由於語言衝突。

+1

檢查您引用的互操作性的版本。然後檢查註冊表HKEY_CLASSES_ROOT - > TypeLib。查找PrimaryInteropAssemblyName並確保您具有相同的版本註冊。如果你有14.0和15.0這可能是你的問題。 – Wheels73

+0

該程序是參考MicroSoft Office Interop Excel版本12.0.0.0,我如何找到該註冊表?對不起,我是新手。 – User001122

+1

你好,完全一樣。只需檢查註冊表。您可以在TypeLib鍵下搜索Microsoft.Office.Interop.Excel,使用(Ctrl F)查找 – Wheels73

回答

0

我嘗試添加此:

System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US"); 

和它的工作,好像這個問題是由於語言衝突。