简体   繁体   中英

C# Convert Excel 2007 (xlsx) file into Excel 2003 (xls) file

I am working on a console application which will convert xlsx file into xls file. I don't want to rename it from xlsx to xls because it will get opened in excel 2007 but it will be shown as corrupted file in excel 2003. Looking for a way which will load the document and then it will be saved as xls format.

My current code Just renames the xlsx to xls

string fileName = @"C:\Users\L-3\Desktop\my.xlsx";
string svfileName = @"C:\Users\L-3\Desktop\ssc\my1.xls";
object oMissing = Type.Missing;
var app = new Microsoft.Office.Interop.Excel.Application();
var wb = app.Workbooks.Open(fileName, oMissing, oMissing,
                oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
wb.SaveAs(svfileName, XlFileFormat.xlOpenXMLTemplate, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
app.Quit();

Your enum is wrong, instead of XlFileFormat.xlOpenXMLTemplate you want XlFileFormat.xlExcel8 , so your code would be like so:

string fileName = @"C:\Users\L-3\Desktop\my.xlsx";
string svfileName = @"C:\Users\L-3\Desktop\ssc\my1.xls";
object oMissing = Type.Missing;
var app = new Microsoft.Office.Interop.Excel.Application();
var wb = app.Workbooks.Open(fileName, oMissing, oMissing,
                oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
wb.SaveAs(svfileName, XlFileFormat.xlExcel8, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
app.Quit();

More info here .

Try with to save with XlFileFormat.xlExcel9795 . You can also use XlFileFormat.xlWorkbookNormal

I've found the following snippet from here :

// Create new XLSX file.
var xlsxFile = new ExcelFile();

// Load data from XLSX file.
xlsxFile.LoadXlsx(fileName + ".xls", XlsxOptions.PreserveMakeCopy);

// Save XLSX file to XLS file.
xlsxFile.SaveXls(fileName + ".xls");

It uses this component .

I think this has the answer you're looking for:

What is the correct `XlFileFormat` enumeration for Excel 97-2003

You're using file format xlOpenXMLTemplate . Try using xlExcel8 instead? That should be the file format for 97-2003 Workbooks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM