ADD REFERENCE
• Interop.Excel
• Interop.Office
• Microsoft.Vbe.Interop
private static Excel.Application app = null;
private static Excel.Workbook workbook = null;
private static Excel.Worksheet worksheet = null;
private static Excel.Range worksheet_range = null;
public static void CreateExcelDoc()
{
try
{
app = new Excel.Application();
app.Visible = true;
workbook = app.Workbooks.Add(1);
worksheet = (Excel.Worksheet)workbook.Sheets[1];
}
catch (Exception ex)
{
throw new ApplicationException(“Error while creating the Excel
file.Message:” + ex.Message);
}
}
public static void CloseDoc(string Path)
{
workbook.Close(true, Path, false);
app.Quit();
if (worksheet != null)
Marshal.ReleaseComObject(worksheet);
if (workbook != null)
Marshal.ReleaseComObject(workbook);
if (app != null)
Marshal.ReleaseComObject(app);
}
private static void InsertSummaryDataToExcel(DataTable dtResult, ref int row)
{
int col=0;
string WorksheetRangeSt = string.Empty;
string WorksheetRangeEnd = string.Empty;
foreach (DataRow dtRow in dtResult.Rows)
{
col=1;
WorksheetRangeSt = “A” + row.ToString();
foreach (DataColumn dtCol in dtResult.Columns)
{
worksheet.Cells[row, col] = dtRow[dtCol.ColumnName].ToString();
col = col + 1;
}
row = row + 1;
}
WorksheetRangeEnd = “E” + row.ToString();
worksheet_range = worksheet.get_Range(WorksheetRangeSt,
WorksheetRangeEnd);
worksheet_range.Borders.Color = System.Drawing.Color.Black.ToArgb();
worksheet_range.Interior.Color = System.Drawing.Color.Ivory.ToArgb();
row = row + 1;
}
My opinion is that you should avoid COM automation (http://www.gemboxsoftware.com/GBSpreadsheet.htm#Automation), especially on server.
Alternatively one could use some 3rd party library. For example,
GemBox.Spreadsheet Free read/write Excel component can be used for XLS / CSV / XLSX for small files.
By: ZeljkoS on September 29, 2008
at 2:39 pm