Home » C# » Insert data into Excel with C#

Insert data into Excel with C#

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.

    _Application docExcel = new Microsoft.Office.Interop.Excel.Application();
    docExcel.Visible = false;
    docExcel.DisplayAlerts = false;

    _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);
    _Worksheet worksheetExcel = (_Worksheet)workbooksExcel.ActiveSheet;

    ((Range)worksheetExcel.Cells["1", "A"]).Value2 = "aa";
    ((Range)worksheetExcel.Cells["1", "B"]).Value2 = "bb";

    workbooksExcel.Save();
    workbooksExcel.Close(false, Type.Missing, Type.Missing);
    docExcel.Application.DisplayAlerts = true;
    docExcel.Application.Quit();

Second example:

 _Application docExcel = new Application{Visible = false};

    dynamic workbooksExcel = docExcel.Workbooks.Open(@"C:\test.xlsx");
    var worksheetExcel = (_Worksheet)workbooksExcel.ActiveSheet;

    ((Range)worksheetExcel.Cells["1", "A"]).Value2 = "test1";
    ((Range)worksheetExcel.Cells["1", "B"]).Value2 = "test2";

    workbooksExcel.Save();
    workbooksExcel.Close(false);
    docExcel.Application.Quit();

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

3 Responses so far.

  1. They are also other alternative since now Microsoft is more open with its format. You can use the Office Open SDK to interact with Microsoft Office document. http://msdn.microsoft.com/en-us/library/office/bb448854(v=office.15).aspx

  2. Philip Lee says:

    You can try ZetExcel.com If you need Excel generation functionality for your .net application

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.