HOWTO · Csharp

How to Write to an Excel File in C#

Learn how to write to an Excel file in C#

On this page

To write data to an Excel workbook from C#, use Microsoft Office Interop when the program is meant to automate the installed Excel desktop application. Interop can create a workbook, populate cells, and save a native .xlsx file. The computer running the program must have Excel installed. If Excel is not available in the deployment environment, use a spreadsheet library that writes workbook files directly.

Choose an Excel-writing approach for your application

Microsoft Office Interop starts Excel and communicates with its object model through COM. Choose it for desktop automation that depends on Excel itself, such as using Excel-specific workbook behavior. It is not a standalone file-writing library: installing an Interop reference in a project does not install Excel on another machine.

For simple tabular data that does not need worksheets, formulas, or formatting, a CSV file is a smaller alternative. Excel can open CSV text, but CSV is not an Excel workbook and cannot store workbook features. The examples below keep these two outcomes separate.

Set Up Microsoft Office Interop in C#

In Visual Studio, add a COM reference to the Microsoft Excel Object Library from the project’s References dialog. The library version depends on the installed Office release. With an early-bound reference, import Microsoft.Office.Interop.Excel, for example with using Excel = Microsoft.Office.Interop.Excel;, to distinguish Excel types from similarly named .NET types.

The workbook example below uses late binding through the Excel COM ProgID, so it does not need that namespace in its source. It still automates Excel and still requires Excel on Windows at runtime. Use the early-bound reference when you want compile-time Excel types and IntelliSense; use late binding when the deployment controls the installed Excel version and you want to avoid a version-specific reference. A reference alone does not make Excel available on a server or other computer.

Create a Workbook and Write Data to Cells

This Interop example creates Excel, adds a workbook, writes a header and two data rows, and saves a native .xlsx file in the system temporary directory. The format value 51 is Excel’s xlOpenXMLWorkbook file format. A GUID makes the output filename unique on each run, so the hidden Excel instance does not wait for an overwrite prompt. The code is intended for Windows with desktop Excel installed and is not shown with runtime output.

using System;
using System.IO;
using System.Runtime.InteropServices;

class Program
{
    static void Main()
    {
        if (Environment.OSVersion.Platform != PlatformID.Win32NT)
        {
            Console.WriteLine("This example requires Windows with Excel installed.");
            return;
        }

        object excelApp = null;
        object workbooks = null;
        object workbook = null;
        object worksheets = null;
        object worksheet = null;
        object cells = null;

        try
        {
            Type excelType = Type.GetTypeFromProgID("Excel.Application");
            if (excelType == null)
            {
                Console.WriteLine("Excel is not registered on this computer.");
                return;
            }

            dynamic app = Activator.CreateInstance(excelType);
            excelApp = app;
            app.Visible = false;
            workbooks = app.Workbooks;
            dynamic books = workbooks;
            workbook = books.Add();
            dynamic book = workbook;
            worksheets = book.Worksheets;
            dynamic sheets = worksheets;
            worksheet = sheets[1];
            dynamic sheet = worksheet;

            cells = sheet.Range["A1:B3"];
            dynamic dataRange = cells;
            object[,] values =
            {
                { "Name", "Age" },
                { "Ava", 28 },
                { "Liam", 31 }
            };
            dataRange.Value2 = values;

            string fileName = "example-" + Guid.NewGuid().ToString("N") + ".xlsx";
            string path = Path.Combine(Path.GetTempPath(), fileName);
            book.SaveAs(path, 51);
            Console.WriteLine("Saved " + Path.GetFileName(path));
        }
        catch (Exception ex)
        {
            Console.WriteLine("Excel operation failed: " + ex.Message);
        }
        finally
        {
            CloseWorkbook(workbook);
            ReleaseComObject(cells);
            ReleaseComObject(worksheet);
            ReleaseComObject(worksheets);
            ReleaseComObject(workbook);
            ReleaseComObject(workbooks);
            QuitExcel(excelApp);
            ReleaseComObject(excelApp);
        }
    }

    static void CloseWorkbook(object value)
    {
        if (value == null) return;
        try { ((dynamic)value).Close(false); }
        catch { }
    }

    static void QuitExcel(object value)
    {
        if (value == null) return;
        try { ((dynamic)value).Quit(); }
        catch { }
    }

    static void ReleaseComObject(object value)
    {
        if (value == null) return;
        try
        {
            if (Marshal.IsComObject(value)) Marshal.FinalReleaseComObject(value);
        }
        catch { }
    }
}

For simple tabular data, a separate CSV example writes comma-separated text that Excel can open. It does not create a workbook or support multiple sheets, formulas, or formatting. The sample values need no CSV quoting; when writing arbitrary text, quote fields containing commas, quotes, or line breaks and double any embedded quotes.

Run this example:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.csv";
        string contents = "Name,Age\nJohn Doe,30\n";
        File.WriteAllText(path, contents);
        Console.WriteLine("Wrote " + path);
    }
}
Wrote example.csv

Write to an Existing Excel File

Open the workbook by its full path, retain the selected range as a COM reference, and release it during cleanup. Save updates the opened file in place; use SaveAs when you want a new path or copy. Replace the sample path with the workbook you intend to edit. This Windows desktop Excel example is not shown with runtime output.

using System;
using System.IO;
using System.Runtime.InteropServices;

class Program
{
    static void Main()
    {
        if (Environment.OSVersion.Platform != PlatformID.Win32NT)
        {
            Console.WriteLine("This example requires Windows with Excel installed.");
            return;
        }

        object excelApp = null;
        object workbooks = null;
        object workbook = null;
        object worksheets = null;
        object worksheet = null;
        object cells = null;
        string path = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
            "report.xlsx");

        try
        {
            if (!File.Exists(path))
                throw new FileNotFoundException("Workbook not found; update the sample path.", path);

            Type excelType = Type.GetTypeFromProgID("Excel.Application");
            if (excelType == null)
                throw new InvalidOperationException("Excel is not registered on this computer.");

            dynamic app = Activator.CreateInstance(excelType);
            excelApp = app;
            app.Visible = false;
            workbooks = app.Workbooks;
            dynamic books = workbooks;
            workbook = books.Open(path);
            dynamic book = workbook;
            worksheets = book.Worksheets;
            dynamic sheets = worksheets;
            worksheet = sheets[1];
            dynamic sheet = worksheet;
            cells = sheet.Range["B2:C2"];
            dynamic selectedCells = cells;
            selectedCells.Value2 = new object[,] { { "Reviewed", DateTime.Today.ToString("yyyy-MM-dd") } };
            book.Save();
            Console.WriteLine("Updated " + Path.GetFileName(path));
        }
        catch (Exception ex)
        {
            Console.WriteLine("Excel operation failed: " + ex.Message);
        }
        finally
        {
            CloseWorkbook(workbook);
            ReleaseComObject(cells);
            ReleaseComObject(worksheet);
            ReleaseComObject(worksheets);
            ReleaseComObject(workbook);
            ReleaseComObject(workbooks);
            QuitExcel(excelApp);
            ReleaseComObject(excelApp);
        }
    }

    static void CloseWorkbook(object value)
    {
        if (value == null) return;
        try { ((dynamic)value).Close(false); }
        catch { }
    }

    static void QuitExcel(object value)
    {
        if (value == null) return;
        try { ((dynamic)value).Quit(); }
        catch { }
    }

    static void ReleaseComObject(object value)
    {
        if (value == null) return;
        try
        {
            if (Marshal.IsComObject(value)) Marshal.FinalReleaseComObject(value);
        }
        catch { }
    }
}

If the source is a CSV, use file I/O and rewrite its rows instead; CSV has no worksheet or cell object model.

Close Excel and Handle Errors

File operations can fail when a path is unavailable or the destination is not writable. Interop can also fail while starting Excel, opening a workbook, writing a cell, or saving, including when the workbook is in use. Catch errors where the application can report or log a useful message. Put workbook closing, Quit, and COM releases in finally; catching an error alone does not clean up Excel. The example guards each cleanup action so a failure while closing does not skip later cleanup attempts.

Keep the Excel application lifetime limited to the operation and avoid retaining extra COM references, such as untracked Range objects. Change the temporary output path to your chosen destination when adapting the example. For formatting, set the relevant worksheet range properties after writing values; CSV output cannot preserve that formatting. The CSV sample also needs file I/O error handling if used in an application.