void ExportToExcel(DataSet ds, string strExcelFileName) { Excel.Application excel = new Excel.Application(); Excel.Worksheet sheet = null; int i = 1; excel.Application.Workbooks.Add(true); sheet = (Excel.Worksheet)excel.Application.Worksheets.get_Item(1); foreach (DataTable table in ds.Tables) { int rowIndex = 1; int colIndex = 0; try { if (i > 1) excel.Worksheets.Add(System.Reflection.Missing.Value, sheet, 1, Excel.XlSheetType.xlWorksheet); } catch (Exception ex) { //MessageBox.Show(ex.Message); return; } foreach (DataColumn col in table.Columns) { colIndex++; excel.Cells[1, colIndex] = col.ColumnName; } foreach (DataRow row in table.Rows) { rowIndex++; colIndex = 0; foreach (DataColumn col in table.Columns) { colIndex++; excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString(); } } sheet = (Excel.Worksheet)excel.Application.Worksheets.get_Item(i); i++; } excel.Visible = false; excel.ActiveWorkbook.SaveAs(strExcelFileName, Excel.XlFileFormat.xlExcel9795, null, null, false, false, Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null); excel.Quit(); excel = null; GC.Collect(); }
dataset2excel
最新推荐文章于 2020-06-25 18:41:40 发布