protected void btnExport_Click(object sender, EventArgs e) 3 { 4 string strMapPath = Server.MapPath("~/"); //获取Web应用程序的物理路径 5 string sourceExcelFileName = strMapPath + "Temp.xls"; //源Excel文件名 6 string targetExcelFileName = strMapPath + @"TempExcel\" + Guid.NewGuid().ToString() + ".xls"; //使用Guid生成全局唯一字符串,作为目标Excel文件的文件名 7 8 File.Copy(sourceExcelFileName, targetExcelFileName); //Copy文件,放在目标文件夹中 9 10 //Excel模型,用来操作Excel文件 11 Microsoft.Office.Interop.Excel.Application excelApp = null; 12 Microsoft.Office.Interop.Excel.Workbook excelWb = null; 13 Microsoft.Office.Interop.Excel.Worksheet excelWs = null; 14 Microsoft.Office.Interop.Excel.Range excelR = null; 15 16 try 17 { 18 excelApp = new Microsoft.Office.Interop.Excel.Application(); 19 excelWb = excelApp.Workbooks.Open(targetExcelFileName); //打开Excel工作簿文件 20 excelWs = (Microsoft.Office.Interop.Excel.Worksheet)(excelWb.Sheets.get_Item(1)); //选择工作簿中第一个工作表 21 22 //向Excel中添加列名 23 for (int i = 0; i < dtbl.Columns.Count; i++) 24 { 25 string rangeName = ((Char)(i + 65)).ToString() + "1"; //计算出单元格的位置(例:第一行第二列在Excel中为B1,即为值为1+65的字符+"1"。) 26 excelR = excelWs.get_Range(rangeName); 27 excelR.Value = dtbl.Columns[i].ColumnName; //在对应单元格中写入值 28 } 29 30 //把每一行数据写入Excel模型中 31 for (int i = 0; i < dtbl.Rows.Count; i++) 32 { 33 for (int j = 0; j < dtbl.Columns.Count; j++) 34 { 35 string rangName = ((Char)(j + 65)).ToString() + (i + 2).ToString(); //表格内容的写入从第二行开始 36 excelR = excelWs.get_Range(rangName); 37 excelR.Value = dtbl.Rows[i][j]; //在Excel中写入对应单元格的内容 38 } 39 } 40 excelWb.Save(); 41 42 } 43 catch (Exception) 44 { 45 Response.Write("<script type='text/javascript'>alert('生成失败!');</script>"); 46 } 47 finally 48 { 49 //关闭Excel,否则Excel文件将无法被打开 50 excelWb.Close(); 51 excelApp.Workbooks.Close(); 52 excelApp.Quit(); 53 } 54 55 //向客户端发送文件... 56 Response.Clear(); 57 Response.AddHeader("Content-Disposition", "attachment;filename=excel.xls"); //设置回发内容为Excel 58 Response.ContentType = "application/ms-excel"; 59 Response.WriteFile(targetExcelFileName); //把刚刚生成的Excel文件写入Http流 60 Response.End(); 61 62 }
2.由于会在临时文件夹中存储Excel文件,所以写了一个类用来清理过期不用的Excel文件:
3.在Golobal.asax中的代码,在Web应用程序启动时开始临时文件清理的服务:
|
|