Public static void exporttoexcel (datatable DT, string filename)
{
// Add excl to reference before doing so !!
Excel. Application Excel = new excel. Application ();
// If the system is excl2007, the added references will be different, Code As follows.
// Microsoft. Office. InterOP. Excel. Application Excel = new Microsoft. Office. InterOP. Excel. Application ();
If (Excel = NULL)
{
}
Else
{
Excel. Workbook xlbook = excel. workbooks. Add (true );
Excel. worksheet xlsheet = (Excel. worksheet) xlbook. worksheets [1];
// Excel. application. workbooks. Add (true );
Int Cols = DT. Columns. count;
Int rows = DT. Rows. count;
// Column
For (int K = 0; k <Cols; k ++)
{
Excel. cells [1, k + 1] = DT. Columns [K]. columnname;
}
// Data
For (INT I = 0; I <rows-1; I ++)
{
For (Int J = 0; j <Cols; j ++)
{
Excel. cells [I + 2, J + 1] = DT. Rows [I] [J]. tostring ();
}
}
Try
{
Xlbook. Saved = true;
Xlbook. savecopyas (filename );
}
Catch
{
}
}
}
Http://files.cnblogs.com/wangdetian168/Interop.Excel.rar