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;
workbook.SaveAs(path);
app.Quit();
ReleaseObject(sheet);
ReleaseObject(workbook);
ReleaseObject(app);
Process.Start(path);
}
private static void ReleaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
Console.WriteLine("Unable to release the Object {0}", ex.ToString());
}
finally
{
GC.Collect();
}
}
}
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;
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#