dataset2excel

来源:互联网 发布:泛微网络 编辑:程序博客网 时间:2024/06/02 19:41
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(); }