一、准備工作
引用:Microsoft.Office.Interop.Excel
准備多個DataTable數據添加到DataSet中。
二、代碼
public void CreateExcel(DataSet ds, string filePath) { //創建excel運行環境 Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook ExcelWorkBook = null; Microsoft.Office.Interop.Excel.Worksheet ExcelWorkSheet = null; ExcelApp.Visible = true; ExcelWorkBook = ExcelApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); //創建excel的sheet名稱 List<string> SheetNames = new List<string>(); SheetNames.Add("人力數據分析"); SheetNames.Add("性別"); SheetNames.Add("省份"); SheetNames.Add("城市"); SheetNames.Add("頁面訪問人數(每天)"); SheetNames.Add("每天具體數據(小時)"); for (int i = 1; i < ds.Tables.Count; i++) ExcelWorkBook.Worksheets.Add(); //添加新的sheet到excel中 for (int i = 0; i < ds.Tables.Count; i++) { int r = 1; // 初始化excel的第一行Position=1 ExcelWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)ExcelWorkBook.Worksheets[i + 1]; //樣式設置 var range = ExcelWorkSheet.get_Range("A1", "K1"); range.Font.Size = 12; range.Font.Name = "黑體"; range.ColumnWidth = 17; //設置單元格的寬度 //把列的名字寫進sheet內 for (int col = 1; col <= ds.Tables[i].Columns.Count; col++) ExcelWorkSheet.Cells[r, col] = ds.Tables[i].Columns[col - 1].ColumnName; r++; //把每一行寫進excel的sheet中 for (int row = 0; row < ds.Tables[i].Rows.Count; row++) //r是excelRow,col是excelColumn { //Excel的行和列開始位置寫Row=1 ,Col=1 for (int col = 1; col <= ds.Tables[i].Columns.Count; col++) ExcelWorkSheet.Cells[r, col] = ds.Tables[i].Rows[row][col - 1].ToString(); r++; } ExcelWorkSheet.Name = SheetNames[i]; } ExcelWorkBook.SaveAs(filePath); ExcelWorkBook.Close(); ExcelApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelWorkSheet); System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelWorkBook); System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApp); GC.Collect(); foreach (System.Diagnostics.Process process in System.Diagnostics.Process.GetProcessesByName("Excel")) process.Kill(); }
三、實現跟谷歌類似文件下載后在最下方顯示下載的文件
public ActionResult OutPutExcel() { ILog log = LogManager.GetLogger(typeof(SystemSetController)); try { DateTime beginTime = Convert.ToDateTime(Request.Form["LiveBeginTime"]); DateTime endTime = Convert.ToDateTime(Request.Form["LiveEndTime"]); long liveId = Convert.ToInt32(Request.Form["liveId"]); //生成的Excel名稱 string fileName = string.Format("{0}.xlsx", DateTime.Now.ToString(@"yyyy-MM-dd-HHmmss")); //獲取數據 DataSet ds = _SystemSetBLL.GetLiveAnalysis(beginTime, endTime, liveId); var filePath = Server.MapPath("~/UploadFile/file/" + fileName); //生成EXCEL _SystemSetBLL.CreateExcel(ds, filePath); Response.Clear(); Response.Charset = "utf-8"; Response.HeaderEncoding = Encoding.UTF8; Response.AddHeader("content-type", "application/x-msdownload"); Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName)); Response.ContentType = "application/vnd.ms-excel"; Response.BinaryWrite(System.IO.File.ReadAllBytes(filePath)); Response.End(); } catch (Exception e) { log.Error("導出數據失敗:" + e.Message); } return null; }
注意:項目部署到服務器上可能會報錯,原因可能是服務器沒安裝excel或者服務器上的excel組件沒有配置好,需要勾選“交互式用戶”及其他,在網上可查,我也忘記了在哪了。
無它,本人學的計算機專業,但好久沒做這一行業,貼出來的有些淺薄,只為幫助有需要的人和鞏固一下。
