Export to Excel in C#
There are many ways to export to Excel from C#. There are even more packages you can buy that do the same.
Instead of buying a package, wrote myself a very basic class to do this. This class can be expanded to allow for a lot more functionality. This is a good start.
What does it use?
You will need references to Microsoft.Office.Interop.Excel (I used version 2), System.IO (for saving the file), and off course, System (for the Garbage Collection).
Open the document
Create the file, then create the workbooks, then the workbook, and then the sheet in that workbook.
private string excelFileName;
private Microsoft.Office.Interop.Excel.Application xls;
private Workbooks workBooks;
private Workbook workBook;
private Worksheet sheet;
object missing = System.Reflection.Missing.Value;
private void Open()
{
xls = new Microsoft.Office.Interop.Excel.Application();
workBooks = xls.Workbooks;
workBook = workBooks.Add(XlWBATemplate.xlWBATWorksheet);
Sheets sheets = workBook.Worksheets;
sheet = (Worksheet)sheets.get_Item(1);
}
Saving the file
After saving the workbook, close and quit and do cleanup.
public void Save()
{
// First delete the file - for not appending
if (File.Exists(excelFileName))
File.Delete(excelFileName);
// Very basic settings
workBook.SaveAs(excelFileName, XlFileFormat.xlWorkbookDefault, missing, missing, missing, missing, XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
workBook.Close(missing, missing, missing);
xls.Workbooks.Close();
xls.Application.Quit();
xls.Quit();
Cleanup();
}
Garbage collection and cleanup
You have to do your own cleaning up when working with Interop.Excel.
Null everything out and then do garbage collection.
private void Cleanup()
{
xls = null;
workBook = null;
sheet = null;
workBooks = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
Selecting a cell
When you reference a call or a range of cells, you start with the sheet you want to select the cells from.
You reference cell with the numeric values y,x (not x,y).
Range range1 = (Range)sheet.Cells[3, 1]; // 3 cells from the top and 1 cell from the left Range range2 = (Range)sheet.Cells[2, 5]; // 2 cells from the top and 5 cells from the left
Selecting a range of cells
A range is selected using alpha numeric values: 'A1' - top left, 'B2' - 2nd column and 2nd row
It is easy to convert numerical values to the Excel Alpha value using the method below.
NOTE: When converting from numeric to alpha, 0 = A, 1 = B, etc...
Range range1 = (Range)sheet.get_Range("A1", "A4"); // first 4 rows in the first column
Range range2 = (Range)sheet.get_Range("C4", "D5"); // for cells - 2 across and 2 down, starting at C4
// Range starting at 2,2 and extending to 4,4
string start = excelColumnLetter(2 - 1) + "2".ToString();
string end = excelColumnLetter(4 - 1) + "4".ToString();
Range range3 = (Range)sheet.get_Range(start, end);
// NOTE: When converting from numeric to alpha, 0 = A, 1 = B, etc...
private string excelColumnLetter(int intCol)
{
int intFirstLetter = ((intCol) / 26) + 64;
int intSecondLetter = (intCol % 26) + 65;
char letter1 = (intFirstLetter > 64) ? (char)intFirstLetter : ' ';
return string.Concat(letter1, (char)intSecondLetter).Trim();
}
Adding content to a cell or range of cells
Create a 'Range' using the 'sheet' you are working on.
Add the content to the 'Value2' property.
There are a lot of visual setting you can use.
A handy chart for the hex colors can be found here.
The method below expects the alpha/numeric value for start and end: "A1", "C44", etc.
public void AddContentToCell(string start, string end, string content, int height, int width)
{
Range range = (Range)sheet.get_Range(start, end);
range.Value2 = content;
range.MergeCells = true;
range.WrapText = true;
range.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignTop;
range.Borders.LineStyle = XlLineStyle.xlDash;
range.Borders.Weight = XlBorderWeight.xlMedium;
range.Borders.Color = 0x060606;
range.Interior.Color = 0xffff8080;
range.ColumnWidth = width;
range.RowHeight = height;
}
Overloads for the AddContent to Cell method
The first overload allows you to select a cell using x and y instead of the alpha/numeric cell reference.
The 2nd overload allows you to select a cell using x and y and use row span and column span.
public void AddContentToCell(int x, int y, string content)
{
if (x < 1) x = 1;
if (y < 1) y = 1;
string start = excelColumnLetter(x - 1) + y.ToString();
string end = start;
AddContentToCell(start, end, content, 50, 30);
}
public void AddContentToCell(int x, int y, int columnspan, int rowspan, string content)
{
if (x < 1) x = 1;
if (y < 1) y = 1;
if (columnspan < 1) columnspan = 1;
if (rowspan < 1) rowspan = 1;
string start = excelColumnLetter(x - 1) + y.ToString();
string end = excelColumnLetter(x + columnspan - 2) + (y + rowspan - 1).ToString();
int width = 30/columnspan;
int height = 50/rowspan;
AddContentToCell(start, end, content, height, width);
}
How to use it?
To use all this, set the file name and call the Open() method. Add stuff to the cells and call the Save() method!
What next?
Next would be to allow us to specify color, borders, etc.