Excel Writing in C# with Interop

Here we cover the basics of writing Excel files in C# with Interop. This can also be useful when you only read Excel files from 3rd parties, for example, for unit testing.

To write an Excel file using Interop in C#, we first need to create an instance of the `Excel.Application` class. Be sure to add a reference to Microsoft.Office.Interop.Excel to your project.

Excel.Application excelApp = new Excel.Application();
if (excelApp != null)
{
    Excel.Workbook excelWorkbook = excelApp.Workbooks.Add();
    Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelWorkbook.Sheets[1];
    // Workbook and worksheet operations
}

Next, we can write data to the cells in this worksheet:

Excel.Range excelRange = excelWorksheet.UsedRange;

excelRange.Cells[1, 1] = "Hello";
excelRange.Cells[1, 2] = "world!";

excelWorkbook.SaveAs(@"C:\temp\excel\myworkbook.xlsx");
excelWorkbook.Close();
excelApp.Quit();

Some useful operations when working with Excel Interop:

  • excelRange.Columns.AutoFit(); — Automatically fits the column width to the maximum length of the cell value in the column.
  • excelRange.Columns[1].ColumnWidth = 20; — Manually set the width of a column.

Unlike CSVHelper and EPPlus, Interop doesn't automatically convert Date/Time to the desired string format. You have to format the Date/Time values manually before writing to the Excel file. Here's how you can do it:

var dateTime = DateTime.Now;

excelRange.Cells[1, 1] = dateTime.ToString("MM/dd/yyyy");