Write Data to Excel using C#
Describes how to write data to an Excel sheet using C#
Introduction
This article will help to write data to Excel using C# without playing with Excel.Application
. With the help of the ExcelFileWriter
class, it is very easy to write data to an Excel sheet.
Background
Those who are lazy to read the help of Excel.Application
in order to write to an Excel sheet can make use of this article and code base.
Using the Code
Firstly, add the reference "Microsoft Excel 11.0 Object Library" by right clicking the References from Visual Studio .NET and select the COM tab. If Excel 11.0 is not there, select Excel 5.0.
The ExcelFileWriter
class is an abstract
class.
In order to write, for example, a set of int
values to an Excel sheet, the steps to follow are listed below:
-
Add ExcelFileWriter.cs into your project.
-
Let's assume you want to add numbers from 1 to 20 which are already populated in the
List
. You can have any data type inside the list. -
Create an object of
ExcelFileWriter
class. Since my collection class,List
, is of typeint
, I create an object ofExcelFileWriter
usingint
. You can use whatever data type you want asExcelFileWriter
is of generic type. -
Call the API,
WriteDataToExcel
and pass the name of the Excel file, the data, the starting column in Excel and the ending column.List<int> myList = new List<int>(); for (int i = 0; i < 20; i++) { myList.Add(i); } ExcelFileWriter<int> myExcel = new ExcelWrite(); myExcel.WriteDateToExcel(@"C:\TEMP\myExcel.xls",myList,"A1","D1");
-
Create a class which derives from
ExcelFileWriter
and make anobject[]
as a member variable. -
Override the functions and properties.
-
Override "Headers" -> return the name of the Column Headers in the Excel sheet:
public override object[] Headers { get { object[] headerName = { "Header1", "Header2", "Header3", "Header4" }; return headerName; }
-
Override
RowCount
andColumnCount
. -
Override
FillRowData
-> fill theexceldata
object:public override void FillRowData(List<int> list) { myRowCnt = list.Count; myExcelData = new object[RowCount + 1, 4]; for (int row = 1; row <= myRowCnt; row++) { for (int col = 0; col < 4; col++) { myExcelData[row, col] = list[row - 1]; } } }
-
Override
ExcelData
:public override object[,] ExcelData { get { return myExcelData; } }
That's it. Build it and Run and you can see that the data is written to the Excel sheet. The important part is you didn't have the headache of understanding the Excel
object.
Hope it helps.
History
- 6th July, 2007: Initial post