Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to Convert Excel to CSV using Interop

0.00/5 (No votes)
19 Nov 2013 1  
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 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here