How to Convert Excel to CSV using Interop






4.92/5 (12 votes)
This simple Tip will give you the Trick to convert Excel file to CSV file using Interop Services.
Introduction
At times, you might need to convert one Excel file to CSV. If you want to do this using Microsoft's Interop Services, then follow this Tip.
Background
This little piece of code is a result of the research during development of one Windows Utility, which uploads Excel sheets to database.
Using the code
First of all, we will check if Excel is installed on the system or not, as Interop works only when Excel is installed on the system. Follow my previous Tip - How to Check Whether Excel is Installed in the System or Not.
To save the file as CSV, we will use Workbook.SaveAs Method
.
Quote:Saves changes to the workbook in a different file.
Type officeType = Type.GetTypeFromProgID("Excel.Application");
if (officeType == null)
{
// Excel is not installed.
// Show message or alert that Excel is not installed.
}
else
{
// Excel is installed.
// Let us continue our work on Excel file conversion.
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
// While saving, it asks for the user confirmation, whether we want to save or not.
// By setting DisplayAlerts to false, we just skip this alert.
app.DisplayAlerts = false;
// Now we open the upload file in Excel Workbook.
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = app.Workbooks.Open(openFileDialog.FileName);
string newFileName = System.IO.Directory.GetCurrentDirectory() + "\\DataMigration.csv";
// Now save this file as CSV file.
excelWorkbook.SaveAs(newFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV);
// Close the Workbook and Quit the Excel Application at the end.
excelWorkbook.Close();
app.Quit();
}
So, the Excel file is now saved as CSV file inside the Current Directory of the Project.
History
- 18 November 2013 - First version submitted for approval