DataSet数据存入指定路径的Excel文件(套用Excel模板)
如题,将DataSet的所有table的数据存入到同一个Excel的不同的Sheet中,一个DataTable对应一个Sheet,每个Sheet的格式参照Excel模板的样式。
具体如下:
1 /// <summary> 2 /// 将DataSet数据写入Excel文件(套用模板并分页) 3 /// </summary> 4 /// <param name="ds">DataSet</param> 5 /// <param name="top">行索引</param> 6 /// <param name="left">列索引</param> 7 /// <param name="lb">显示数据写入的进度label标签</param> 8 public void DataSetToExcel(DataSet ds, int top, int left, Label lb) 9 { 10 11 int sheetCount = ds.Tables.Count; 12 DateTime beforeTime; 13 DateTime afterTime; 14 15 16 //创建一个Application对象并使其可见 17 beforeTime = DateTime.Now; 18 Excel.Application app = new Excel.Application(); 19 app.Visible = false; 20 afterTime = DateTime.Now; 21 22 //打开模板文件,得到WorkBook对象 23 Excel.Workbook workBook = app.Workbooks.Open(templetFile, missing, missing, missing, missing, missing, 24 missing, missing, missing, missing, missing, missing, missing); 25 26 //得到WorkSheet对象 27 Excel.Worksheet workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(1); 28 29 //复制sheetCount-个WorkSheet对象 30 for (int i = 1; i < sheetCount; i++) 31 { 32 ((Excel.Worksheet)workBook.Worksheets.get_Item(i)).Copy(missing, workBook.Worksheets[i]); 33 } 34 35 //将源DataTable数据写入Excel#region 将源DataTable数据写入Excel 36 for (int i = 1; i <= sheetCount; i++) 37 { 38 39 //末行索引 40 int colCount = ds.Tables[i-1].Columns.Count; 41 42 //获取要写入数据的WorkSheet对象,并重命名 43 Excel.Worksheet sheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i); 44 sheet.Name = ds.Tables[i-1].TableName; 45 46 //将dt中的数据写入WorkSheet 47 for (int j = 0; j < ds.Tables[i-1].Rows.Count; j++) 48 { 49 for (int k = 0; k < colCount; k++) 50 { 51 sheet.Cells[top + j, left + k] = ds.Tables[i-1].Rows[j][k].ToString(); 52 } 53 lb.Text = "Saving lines: " + sheet.Name + "+" + (1 + j) + "/" + (ds.Tables[i-1].Rows.Count); 54 } 55 } 56 57 //输出Excel文件并退出 58 try 59 { 60 workBook.SaveAs(outputFile, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing); 61 workBook.Close(null, null, null); 62 app.Workbooks.Close(); 63 app.Application.Quit(); 64 app.Quit(); 65 66 System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet); 67 System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook); 68 System.Runtime.InteropServices.Marshal.ReleaseComObject(app); 69 70 workSheet = null; 71 workBook = null; 72 app = null; 73 74 GC.Collect(); 75 } 76 catch (Exception e) 77 { 78 throw e; 79 } 80 finally 81 { 82 Process[] myProcesses; 83 DateTime startTime; 84 myProcesses = Process.GetProcessesByName("Excel"); 85 86 //得不到Excel进程ID,暂时只能判断进程启动时间 87 foreach (Process myProcess in myProcesses) 88 { 89 startTime = myProcess.StartTime; 90 91 if (startTime > beforeTime && startTime < afterTime) 92 { 93 myProcess.Kill(); 94 } 95 } 96 } 97 98 }