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)
{
}
else
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
app.DisplayAlerts = false;
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = app.Workbooks.Open(openFileDialog.FileName);
string newFileName = System.IO.Directory.GetCurrentDirectory() + "\\DataMigration.csv";
excelWorkbook.SaveAs(newFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV);
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