First we should add a reference to Microsoft.Office.Interop
using Excel =
Microsoft.Office.Interop.Excel;
private void create_excel(DataTable
dt, string fname)
{
//if
(string.IsNullOrEmpty(fname))
//{
// fname = Application.StartupPath +
"\\pdftemplate_" + DateTime.Now.Ticks + ".xls";
//}
//else {
fname += ".xls"; }
//fullfilename
= fname;
fname = GenarateFilename(fname, ".xls");
fullfilename = fname;
Excel.Application
xlApp;
Excel.Workbook
xlWorkBook;
Excel.Worksheet
xlWorkSheet;
object
misValue = System.Reflection.Missing.Value;
xlApp = new
Excel.ApplicationClass();
xlWorkBook =
xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range
chartRange;
for
(int i = 0; i < dt.Columns.Count; i++)
{
xlWorkSheet.Cells[1, i + 1] =
dt.Columns[i].ColumnName;
}
chartRange = xlWorkSheet.get_Range("A1", cellcount(dt.Columns.Count) + "1");
chartRange.Font.Bold = true;
chartRange.Font.Color =
System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Maroon);
for
(int i = 0; i < dt.Rows.Count; i++)
{
for
(int j = 0; j < dt.Columns.Count; j++)
{
xlWorkSheet.Cells[i + 2, j
+ 1] = dt.Rows[i][j].ToString();
}
}
chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlMedium, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
xlWorkBook.SaveAs(fname, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue,
misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive,
misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}





0 comments:
Post a Comment