How to Create and Write Excel File in C#

How to Create and Write Excel File in C#

First step is to add necessary references to the project.

1. Right click References and press Add References item in the menu.
2. Go to COM Tab and select Type Libraries.
3. Select the ticks of
    - Microsoft Excel 14.0 Object Library
    - Microsoft Office 14.0 Object Library

Required using statements:

using Microsoft.Office.Interop.Excel;

Here is the example code:

class Program
    static void Main(string[] args)
        object misValue = System.Reflection.Missing.Value;
        var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "deneme.xlsx");

        var app = new Application();
        var workbook = app.Workbooks.Add(misValue);
        var sheet = (Worksheet)workbook.ActiveSheet;

        // add new sheet after the existing sheets
        // sheet = app.Worksheets.Add(Missing.Value, app.Worksheets[app.Worksheets.Count], Missing.Value, Missing.Value);

        // choose existing sheet at index page
        // var iter = app.Worksheets.GetEnumerator();
        // for (int i = 0; i < page + 1; ++i)
        //     iter.MoveNext();
        // sheet = iter.Current;

        sheet.Cells[1, 1] = 5;




    private static void ReleaseObject(object obj)
            obj = null;
        catch (Exception ex)
            obj = null;
            Console.WriteLine("Unable to release the Object {0}", ex.ToString());

Adding a line or bar chart to excel worksheet

Excel.ChartObjects xlCharts = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(10, 80, 300, 250);
Excel.Chart chartPage = myChart.Chart;

chartRange = xlWorkSheet.get_Range("A1", "d5");
chartPage.SetSourceData(chartRange, Missing.Type);
chartPage.ChartType = Excel.XlChartType.xlColumnClustered;

added 7 years 4 months ago

Contents related to 'How to Create and Write Excel File in C#'

How to Open and Read From Excel File in C#: How to open and read from excel file in c#

- How to make bold the text before colon character in Microsoft Word
- Generate object from xml in c#
- 24 Useful Distinct Color Codes
- How to draw an arrow with DrawLine command
- How to write Snake game in C#?
- Break Parallel Foreach Earlier
- How to find all Stored Procedures having a given text inside
- How to Create and Write Excel File in C#
- Extension Methods
- Microsoft Code Contracts
- VersaFix
- QuickFIX
- fix4net
- Converting String to Double in C#
- C# File Operations, C# Input Output (C# I/O)