將DataTable 數據導出到Execl格式
源代碼如下:
首先new一個保存的對話框:
private System.Windows.Forms.SaveFileDialog m_objSave = new SaveFileDialog();
//導出數據方法
public void m_mthExportToExecl()
{
this.m_objSave.DefaultExt = "xls";
this.m_objSave.Filter = "Excel文件(*.xls)|*.xls";
if (this.m_objSave.ShowDialog() == DialogResult.OK)
{
m_mthDoExport(dtFindCharge, m_objSave.FileName);
}
}
//具體導出的方法
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);
//將DataTable的列名導入Excel表第一行
foreach (DataColumn dc in dtSource.Columns)
{
columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;
}
//將DataTable中的數據導入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;
}
}