Insert data into Excel with C#<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Insert data into Excel with C#

Posted on: February 16, 2012

It's possible with .Net to write data into Excel's cells. This can be done by using the library of Microsoft.Office.

The first step is to add a reference into you project by right clicking on the References folder and add the COM of Microsoft Office Excel.

Here is a small example that show you how to open an Excel worksheet and add value to 2 cells. It will save the content back the to same file. The first approach do not use the Dynamic keyword which will be more verbose. The second example, do the same thing in less code by using Dynamic.

1_Application docExcel = new Microsoft.Office.Interop.Excel.Application();
2docExcel.Visible = false;
3docExcel.DisplayAlerts = false;
4
5_Workbook workbooksExcel = docExcel.Workbooks.Open(@"C:\\test.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
6_Worksheet worksheetExcel = (_Worksheet)workbooksExcel.ActiveSheet;
7
8((Range)worksheetExcel.Cells["1", "A"]).Value2 = "aa";
9((Range)worksheetExcel.Cells["1", "B"]).Value2 = "bb";
10
11workbooksExcel.Save();
12workbooksExcel.Close(false, Type.Missing, Type.Missing);
13docExcel.Application.DisplayAlerts = true;
14docExcel.Application.Quit();

Second example:

1_Application docExcel = new Application{Visible = false};
2
3dynamic workbooksExcel = docExcel.Workbooks.Open(@"C:\\test.xlsx");
4var worksheetExcel = (_Worksheet)workbooksExcel.ActiveSheet;
5
6((Range)worksheetExcel.Cells["1", "A"]).Value2 = "test1";
7((Range)worksheetExcel.Cells["1", "B"]).Value2 = "test2";
8
9workbooksExcel.Save();
10workbooksExcel.Close(false);
11docExcel.Application.Quit();