1. 程式人生 > >前端利用Post方式與後臺互動匯出Excel

前端利用Post方式與後臺互動匯出Excel

最近做了一個功能,將頁面查詢的表格資料匯出到excel表格中,利用NOPI的方法做匯出功能。

1.下載NOPI.dll並引用到專案中。

2.前端頁面的匯出方法:

 //匯出
    function btnExport() {
        var colArr = [];
        //這裡寫獲取頁面表格欄位的顯示名稱,並存到colArr數組裡面,為了方便在後臺迴圈渲染。

        if(colArr.length == 0){
            alert("請查詢要匯出的資料!");
            return;
       }
        
//這裡是要傳到後臺查詢資料的查詢條件,根據自己所要傳的引數進行修改,ColNames這個傳上面獲取欄位顯示名稱的陣列
var searchdata = { AreaNO: $('#chooseBox').val(), StartTime: sDateResult, EndTime: sDateResult, ColNames: colArr };
//QueryType可以自己定義,後臺會根據這個進行判斷匯出對應的頁面資料
var postData = { QueryType: 1, FileName: "你想要匯出的檔名稱", QueryParms: JSON.stringify(searchdata) }; $.post(
"/Export/ExcelExport", postData, function (data) { if (data) { location.href = '/Export/GetExcelFile?download=' + data; //根據後臺返回檔名稱進行下載 } }); }

3.後臺的對應的方法:

public class ExportController : Controller
    {
        /// <summary>
        /// 下載Excel檔案
        
/// </summary> /// <param name="download"></param> /// <returns></returns> public FileResult GetExcelFile(string download) { FileStream fs = (FileStream)Session[download]; Session.Remove(download); return File(fs, "application/vnd.ms-excel", download); } /// <summary> /// 匯出Excel表格 /// </summary> /// <param name="QueryType"></param> /// <param name="FileName"></param> /// <param name="QueryParms"></param> /// <returns></returns> public string ExcelExport(int queryType, string fileName, string queryParms) { QueryParmsObj o = new QueryParmsObj(); QueryParmsObj request = (QueryParmsObj)JsonToObject(queryParms, o); System.IO.FileStream fs; fileName = fileName + "_匯出資料_" + DateTime.Now.ToString("yyyyMMddHHmmss"); string download = string.Format(@"{0}.xlsx", fileName); try { //建立Excel檔案的物件 IWorkbook workbook = new HSSFWorkbook(); //根據不同的型別匯出不同的報表 if (queryType == 1) { //這裡通過引數查詢獲取要匯出的資料 var otherController = DependencyResolver.Current.GetService<FinancialAnalysisController>(); var response = otherController.FinancialAnalysisMConerlistData(request.AreaNO,request.StartTime,request.EndTime,null,null,null,null); JObject list = (JObject)JsonConvert.DeserializeObject(response); GetRowsOfType1(workbook, list, fileName,request.ColNames); } else if (queryType == 2) { } string pathString = Request.ApplicationPath; var mappath = Server.MapPath(pathString); var domainPath = AppDomain.CurrentDomain.GetData("DataDirectory").ToString(); if (!Directory.Exists(string.Format("{0}\\Report", domainPath))) { Directory.CreateDirectory(string.Format("{0}\\Report", domainPath)); } string filePath = String.Format(@"{0}\\Report\\{1}_{2}.xlsx", domainPath, fileName, DateTime.Now.ToString("yyyyMMddHHmmss")); // 寫入到客戶端 fs = new FileStream(filePath, FileMode.OpenOrCreate); workbook.Write(fs); fs.Seek(0, SeekOrigin.Begin); } catch (Exception) { throw new Exception(); } Session[download] = fs; return download; } /// <summary> /// 匯出格式和資料渲染 /// </summary> /// <param name="workbook"></param> /// <param name="list"></param> /// <param name="name"></param> /// <param name="colNames"></param> /// <returns></returns> private IWorkbook GetRowsOfType1(IWorkbook workbook, JObject list, string name,List<string> colNames) { //新增一個sheet ISheet sheet1 = workbook.CreateSheet("Sheet1"); int colSpan = colNames.Count-1; SetSheetTitle(workbook, sheet1, name,colSpan); IRow row2 = sheet1.CreateRow(2); for (var i = 0; i < colNames.Count; i++) { row2.CreateCell(i).SetCellValue(colNames[i]); } //將資料逐步寫入sheet1各個行 var listData = list["data"]; for (int i = 0; i < listData.ToList().Count; i++) { IRow rowtemp = sheet1.CreateRow(i + 3); var cellVal = ""; for (int j = 0; j < listData[i].ToList().Count; j++) { cellVal = listData[i].ToList()[j].First.ToString(); rowtemp.CreateCell(j).SetCellValue(cellVal); } } return workbook; } /// <summary> /// 設定匯出Excel標題 /// </summary> /// <param name="workbook"></param> /// <param name="sheet1"></param> /// <param name="name"></param> private void SetSheetTitle(IWorkbook workbook, ISheet sheet1, string name,int colSpan) { //給sheet1新增第一行的頭部標題 IRow row0 = sheet1.CreateRow(0); row0.HeightInPoints = 30;//行高 row0.CreateCell(0).SetCellValue(name);//建立第一列 IFont font = workbook.CreateFont(); //建立一個字型樣式物件 font.FontHeightInPoints = 17;//字型大小 font.Boldweight = short.MaxValue;//字型加粗 ICellStyle style = workbook.CreateCellStyle();//建立樣式物件 style.SetFont(font); //將字型樣式賦給樣式物件 style.Alignment = HorizontalAlignment.Center; row0.Cells[0].CellStyle = style; ; //把樣式賦給單元格 CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, colSpan); sheet1.AddMergedRegion(cellRangeAddress); IRow row1 = sheet1.CreateRow(1); row1.HeightInPoints = 20;//行高 row1.CreateCell(0).SetCellValue("製表日期:" + DateTime.Now.Date.ToString("yyyy-MM-dd")); font = workbook.CreateFont(); //建立一個字型樣式物件 font.FontHeightInPoints = 13;//字型大小 font.Boldweight = short.MaxValue;//字型加粗 style = workbook.CreateCellStyle();//建立樣式物件 style.SetFont(font); row1.Cells[0].CellStyle = style; cellRangeAddress = new CellRangeAddress(1, 1, 0, colSpan); sheet1.AddMergedRegion(cellRangeAddress); } /// 把Json文字轉為實體 public static object JsonToObject(string jsonString, object obj) { return JsonConvert.DeserializeObject(jsonString, obj.GetType()); } /// <summary> /// 查詢引數實體 /// </summary> private class QueryParmsObj { public string AreaNO { get; set; } public string StartTime { get; set; } public string EndTime { get; set; } public List<string> ColNames { get; set; } } }