由DataTable表导出Excel的简单方法,记录以免遗忘。
private void exportTab(DataTable db)
{
try
{
DataRow[] dr = db.Select();
string columnName = null;
Excel.Application app = new Excel.Application();
app.Visible = false;
Excel.Workbooks workBooks = app.Workbooks;
Excel.Workbook workBook = workBooks.Add(tempLatePath);
Excel.Sheets xslSheets = workBook.Worksheets;
Excel._Worksheet workSheet = (Excel._Worksheet)xslSheets.get_Item(1);
outFileName = outPath.Substring(outPath.LastIndexOf("\") + 1);
//workSheet.Name = outFileName;
object[,] m_objectData = new object[db.Rows.Count + 1, db.Columns.Count - 1];
Excel.Range m_objRange = workSheet.get_Range("A1", this.missing);
m_objRange = m_objRange.get_Resize(db.Rows.Count + 1, db.Columns.Count - 1);
Excel.Font m_objFont = m_objRange.Font;
m_objFont.Bold = false;
for (int i = 0; i < workSheet.UsedRange.Columns.Count; i++)
{
m_objectData[0, i] = workSheet.Cells[1, i + 1].Text;
}
for (int i = 0; i < db.Rows.Count; i++)
{
for (int j = 0; j < db.Columns.Count - 1; j++)
{
columnName = m_objectData[0, j].ToString();
m_objectData[i + 1, j] = dr[i][columnName].ToString();
}
}
m_objRange.Value2 = m_objectData;
workBook.SaveAs(this.outPath, this.missing, null, null, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
this.missing, this.missing, this.missing, this.missing, this.missing);
workBook.Close(null, null, null);
app.Workbooks.Close();
app.Application.Quit();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
workSheet = null;
workBook = null;
app = null;
commonLib.setbusy(false);
MessageBox.Show("导出成功!");
}
catch (Exception e)
{
throw e;
}
}