0
votes

I'm trying to export dataGrid into an excel file but I keep getting this error:

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

Here's my code:

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;

            }
        }

How to correct this?

---------------------------EDIT-----------------------------------

I tried adding this :

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

and it worked, it seems like the problem was due to a language conflict.

1
Check what version of the interop you have referenced. Then check the registry HKEY_CLASSES_ROOT --> TypeLib. Look for the PrimaryInteropAssemblyName and ensure you have the same verison registered. If you have 14.0 and 15.0 this could be your issue. - Wheels73
The program is referencing MicroSoft Office Interop Excel version 12.0.0.0, how do i find that registry? Sorry I'm new to this. - CodingLife
Hello, exactly the same. Just check the registry. You can search for Microsoft.Office.Interop.Excel under the TypeLib key, Use (Ctrl F) for find - Wheels73
So seems like you are referencing the wrong version. Delete the ref from your project and add a new ref to C:\Program Files (x86)\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA\Office14\Microsoft.Office.Interop.Excel.dll. Also ensure that v14.00 is the only reg entry. Delete the other key for 12 if it exists. - Wheels73

1 Answers

0
votes

I tried adding this :

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

and it worked, it seems like the problem was due to a language conflict.