C# How to create an Excel file and write data into it

In this short tutorial, I am going to explain how to create a new Excel file and write some data in a C# application.

First of all, you need to add a reference to the Microsoft.Office.Interop.Excel library to your project. You can do it by clicking with the right mouse button on the Reference folder in your project in the Solution Explorer and selecting the option Add Reference. In the Reference Manager use the search field to search for the mentioned library. Likely, you find multiple versions of the library. For this tutorial, I used the version (15.0.0.0). Select the library by placing a tick in the checkbox left of the library name and click OK.

To create a new Excel file, we first need to execute a new instance of the Excel application (alternatively, you can also search for an existing one, yet we do not consider thís option here). A new instance of the Excel application can be created as follows:

Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();

Having the instance of the Excel application, we can create a new workbook and access the worksheet. The created workbook contains per default one worksheet that has the index 1 in the Worksheets array:

Microsoft.Office.Interop.Excel.Workbook workbook = app.Workbooks.Add();
Microsoft.Office.Interop.Excel.Worksheet worksheet = workbook.Worksheets[1];

Now, we can write some data into the worksheet. We are going to create a 10×10 times table:

worksheet.Name = "TimesTable";
for (int row = 1; row < 10; row++)
{
    for(int column = 1; column < 10; column++)
    {
        worksheet.Cells[row, column].Value = row * column;
    }
}

Finally, we save the workbook and close the Excel application.

workbook.SaveAs("E:\TimesTable.xls");
workbook.Close();
app.Quit();

That’s all!

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.