Write data to Web Excel using .NET

Here is an example of .NET code that writes data to Microsoft Excel using the Microsoft.Office.Interop.Excel library:

using System;
using System.IO;
using System.Reflection;
using Microsoft.Office.Interop.Excel;

namespace ExcelWriter
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of Excel application
            Application excel = new Application();

            // Create a new Workbook
            Workbook workbook = excel.Workbooks.Add();

            // Select the first Worksheet
            Worksheet worksheet = workbook.Worksheets[1];

            // Write data to the Worksheet
            worksheet.Cells[1, 1] = "Name";
            worksheet.Cells[1, 2] = "Age";
            worksheet.Cells[2, 1] = "John";
            worksheet.Cells[2, 2] = 30;
            worksheet.Cells[3, 1] = "Mary";
            worksheet.Cells[3, 2] = 25;

            // Save the Workbook
            string path = Path.Combine(Environment.GetFolderPath(
                 Environment.SpecialFolder.Desktop), "Data.xlsx");
            workbook.SaveAs(path);

            // Close the Workbook and Excel application
            workbook.Close();
            excel.Quit();

            // Release COM objects to prevent memory leaks
            ReleaseObject(worksheet);
            ReleaseObject(workbook);
            ReleaseObject(excel);

            Console.WriteLine($"Data has been written to {path}");
        }

        private static void ReleaseObject(object obj)
        {
            try
            {
                Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                Console.WriteLine($"Exception occurred while releasing object: {ex.Message}");
            }
            finally
            {
                GC.Collect();
            }
        }
    }
}

This code creates a new Excel workbook, writes some data to the first worksheet, saves the workbook to the user’s desktop, and then closes Excel. Add a reference to the Microsoft.Office.Interop.Excel library in your project before you can use it. Also, make sure to release COM objects to prevent memory leaks.

Pamai Tech
Turning ideas into Reality

Products

Office Add-in

Enterprise Solutions

Cloud Consulting

UI UX Design

Data Transformation

Services

FAQ's

Privacy Policy

Terms & Condition

Team

Contact Us

Company

About Us

Services

Features

Our Pricing

Latest News

© 2025 Pamai Tech