/// <summary> /// 把数据文件导入到.xls文件 /// </summary> /// <param name="ds"></param> public void ExportToExcel(DataSet ds) { if(ds.Tables.Count!=0) { //生成.xls文件完整路径名 string tempFileName = GetTempFileName(); object filename = EXCELPATH+tempFileName+EXCELPOSTFIX; object Nothing = System.Reflection.Missing.Value; //创建excel文件,文件名用系统时间生成精确到毫秒 Excel.Application myExcel = new Excel.ApplicationClass(); myExcel.Application.Workbooks.Add(Nothing); try { //把Dataset中的数据插入excel文件中 int totalCount = 0; for(int k =0;k<ds.Tables.Count;k++) { int row = ds.Tables[k].Rows.Count; int column = ds.Tables[k].Columns.Count; for(int i = 0;i<column;i++) { myExcel.Cells[totalCount+2,1+i] = ds.Tables[k].Columns[i].ColumnName; } for(int i = 0;i<row;i++) { for(int j =0;j<column;j++) { myExcel.Cells[totalCount+3+i,1+j] = "'" + ds.Tables[k].Rows[i][j].ToString(); } } totalCount = totalCount + row +4; } try { //保存excel文件到指定的目录下,文件名用系统时间生成精确到毫秒 myExcel.ActiveWorkbook._SaveAs(filename,Nothing,Nothing,Nothing,Nothing,Nothing,XlSaveAsAccessMode.xlExclusive,Nothing,Nothing,Nothing,Nothing); } catch { System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件: "+EXCELPATH+tempFileName+EXCELPOSTFIX); return; } //让生成的excel文件可见 myExcel.Visible = true; } catch(Exception e) { System.Windows.Forms.MessageBox.Show("向excel文件中写入数据出错: " + e.Message); } } else { System.Windows.Forms.MessageBox.Show("No Data"); } } |