如何将DataTable在客户端导出成Excel
如题,请各位大虾指导下初学者,谢谢!
程序代码:
public void CreateExcel(System.Data.DataTable dt, string fileName)//创建excel { Object missing = Missing.Value; Microsoft.Office.Interop.Excel.Application m_objExcel = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbooks m_objWorkBooks = m_objExcel.Workbooks; Microsoft.Office.Interop.Excel.Workbook m_objWorkBook = m_objWorkBooks.Add(true); Microsoft.Office.Interop.Excel.Sheets m_objWorkSheets = m_objWorkBook.Sheets; ; Microsoft.Office.Interop.Excel.Worksheet m_objWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)m_objWorkSheets[1]; int intFeildCount = dt.Columns.Count; for (int i = 0; i < intFeildCount; i++) { m_objWorkSheet.Cells[1, i + 1] = dt.Columns[i].ToString(); } for (int intRowCount = 0; intRowCount < dt.Rows.Count; intRowCount++) { for (int intCol = 0; intCol < dt.Columns.Count; intCol++) { m_objWorkSheet.Cells[intRowCount + 2, intCol + 1] = dt.Rows[intRowCount][intCol].ToString(); } } m_objWorkBook.SaveAs(fileName, missing, missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing); m_objExcel = null; MessageBox.Show("完成"); }