Export DataTable data to Execl format
The source code is as follows:
First, a new dialog box is saved:
Private System. Windows. Forms. SaveFileDialog m_objSave = new SaveFileDialog ();
// Data export Method
Public void m_mthExportToExecl ()
{
This. m_objSave.DefaultExt = "xls ";
This. m_objSave.Filter = "Excel file (*. xls) | *. xls ";
If (this. m_objSave.ShowDialog () = DialogResult. OK)
{
M_mthDoExport (dtFindCharge, m_objSave.FileName );
}
}
// Specific export Method
Private void m_mthDoExport (DataTable dtSource, string strFileName)
{
Int rowNum = dtSource. Rows. Count;
Int columnNum = dtSource. Columns. Count;
Int rowIndex = 1;
Int columnIndex = 0;
If (dtSource = null | string. IsNullOrEmpty (strFileName ))
{
Return;
}
If (rowNum> 0)
{
Excel. Application xlApp = new Excel. ApplicationClass ();
XlApp. DefaultFilePath = "";
XlApp. DisplayAlerts = true;
XlApp. SheetsInNewWorkbook = 1;
Excel. Workbook xlBook = xlApp. Workbooks. Add (true );
// Import the column name of DataTable into the first row of the Excel table
Foreach (DataColumn dc in dtSource. Columns)
{
ColumnIndex ++;
XlApp. Cells [rowIndex, columnIndex] = dc. ColumnName;
}
// Import data in DataTable to Excel
For (int I = 0; I <rowNum; I ++)
{
RowIndex ++;
ColumnIndex = 0;
For (int j = 0; j <columnNum; j ++)
{
ColumnIndex ++;
XlApp. Cells [rowIndex, columnIndex] = dtSource. Rows [I] [j]. ToString ();
}
}
XlBook. SaveCopyAs (strFileName );
XlApp = null;
XlBook = null;
}
}