Load a comma-separated value (CSV) in Excel in C#

This isn't too hard once you know the tricks. First at design time, add a reference to the Excel object library. To do that, open the Project menu and select Add Reference. On the Add Reference dialog, select the COM tab and add a reference to "Microsoft Excel 12.0 Object Library" (or whatever version you have installed on your system).

To make using the library easy, add the following using statement at the top of your code.

using Excel = Microsoft.Office.Interop.Excel;

This lets you use the word "Excel" to mean Microsoft.Office.Interop.Excel in your code.

The example uses the following code to open the CSV file.

// Open a delimited file in Excel.
private void btnLoad_Click(object sender, EventArgs e)
{
// Get the Excel application object.
Excel.Application excel_app = new Excel.ApplicationClass();

// Make Excel visible (optional).
excel_app.Visible = true;

// Open the file.
excel_app.Workbooks.Open(
txtFile.Text, // Filename
Type.Missing,
Type.Missing,
Excel.XlFileFormat.xlCSV, // Format
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
txtDelimiter.Text, // Delimiter
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing);
}

The code first creates an instance of the Excel application. It then uses that object's Workbooks.Open method to open the file. The tricks here are:

  • Set the format to xlCSV
  • Indicate the delimiter (commas, tabs, semicolons, or whatever)
  • Use Type.Missing for any parameter that you want to omit from the call

that's all there is to this example. Once you have the file open, you could use other Excel methods to manipulate the data such as copying values into other workbooks, saving the data in a new file, or loading the data into your C# program.

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.