Hi all.
I attached a code creating file from datatable.
I have a problem saving Excel file in c# using Microsoft.Office.Interop.Excel.
When I'm saving the file as Exsel 2003 (xls) format the file is OK.
When I'm saving the file as Excel 2007 (xlsx) format I get error massage from office Excel 2007 regarding the file structure.
what should I change in the below code in order to save the file in 2007 format.
thanks in advance.

Microsoft.Office.Interop.Excel.Application app;
            Microsoft.Office.Interop.Excel.Workbook workBook;
            Microsoft.Office.Interop.Excel.Worksheet workSheet;
            object misValue = System.Reflection.Missing.Value;
            app = new Microsoft.Office.Interop.Excel.ApplicationClass();
            app.Visible = false;
            workBook = app.Workbooks.Add(misValue);

            workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Worksheets.get_Item(1);

            int i = 0;
            int j = 0;
                foreach (DataRow row in dataTable.Rows)
                    foreach (DataColumn column in dataTable.Columns)
                        //writing the column name
                        if (i == 0)
                            workSheet.Cells[i + 1, j + 1] = usersDataTable.Columns[j].ColumnName;
                        //writing the table
                        workSheet.Cells[i + 2, j + 1] = row[column].ToString();
                    j = 0;
                try//saving file
                    FileInfo f = new FileInfo(path);
                    if (f.Exists)
                        f.Delete(); // delete the file if it already exist.
                    workBook.SaveAs(path, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

Recommended Answers

All 5 Replies

Are you using the correct version of the Interop Assemblies?

Are you using the correct version of the Interop Assemblies?

Yes, I'm using the last Interop version that I have in Visual studio 2008. version 12.

Found a solution for this.
In order to save 2007 xslx file I should call the "saveAs" method using other second parameter parameter.
the second parameter should be: "Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook".
If you are saving Excel 2003 or 2007 based on users choice, you should distinguish it and call the function according yo user's choice.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.