<a class="btn btn-app" onclick="exportExcel()"><i class="fa fa-edit"></i>導出Excel</a>
貼下面的代碼之前,我想說一下
我的數據是主外鍵關系,有多張表關聯,所以在做數據的時候,發現很多問題,讀取的時候,它會自動讀取所有的數據。
當然這不能滿足我導出之后的要求,我只需要導出我要的字段即可,所以我進行了數據處理。
//導出Excel function exportExcel() { var rows = $("#saleGrid").datagrid("getRows"); for (var i = 0; i < rows.length; i++) { //進行數據處理 if (isArray(rows[i].OrganizedId)) { rows[i].OrganizedId = rows[i].OrganizedId[0]; } if (isArray(rows[i].CustomerId)) { rows[i].CustomerId = rows[i].CustomerId[0]; } if (rows[i].AdvanceDate != null) { var unix = rows[i].AdvanceDate.replace("/Date(", "").replace(")/", ""); var un = unix.substring(0, 10); var newDate = new Date(); newDate.setTime(un * 1000); rows[i].AdvanceDate = newDate.toLocaleString(); } if (rows[i].OrderDate != null) { var unix = rows[i].OrderDate.replace("/Date(", "").replace(")/", ""); var un = unix.substring(0, 10); var newDate = new Date(); newDate.setTime(un * 1000); rows[i].OrderDate = newDate.toLocaleString(); } if (rows[i].RetainageDate != null) { var unix = rows[i].RetainageDate.replace("/Date(", "").replace(")/", ""); var un = unix.substring(0, 10); var newDate = new Date(); newDate.setTime(un * 1000); rows[i].RetainageDate = newDate.toLocaleString(); } //移除不要的字段 delete rows[i].SaleAtts; delete rows[i].SaleOrderId; delete rows[i].SaleOrderItems; delete rows[i].SaleStatus; delete rows[i].UserName; delete rows[i].Customer; delete rows[i].AddDate; } var bodyData = JSON.stringify(rows); //轉成json字符串 //替換中文標題 var a = bodyData.replace(/SaleOrderNo/g, "訂單編號").replace(/OrderType/g, "訂單類型").replace(/FromWhere/g, "訂單來源") .replace(/OrganizedId/g, "機構").replace(/SaleUser/g, "銷售員").replace(/SaleTc/g, "銷售提成").replace(/OrderDate/g, '訂單日期') .replace(/ContractNo/g, "合同編號").replace(/Amount/g, "總額").replace(/Advance/g, "首付款").replace(/AdvanceDate/g, "首付款日期") .replace(/PayMethod/g, "支付方式").replace(/Retainage/g, "尾款").replace(/RetainageDate/g, "尾款日期").replace(/InlayPrice/g, "鑲嵌款") .replace(/CustManager/g, "客戶經理").replace(/EquityNo/g, "認股書編號").replace(/LogisticsTotal/g, "物流費用") .replace(/Remarks/g, "備注").replace(/CompletedStatus/g, "狀態").replace(/CustomerId/g, "終端客戶"); var postData = { data: a }; $.ajax({ type: "POST", url: "ExportExcel", data: postData, success: function (data) { if (data == "1") { layer.msg("操作成功,文件在桌面!", { icon: 6, time: 2000, }); } else if (data == "-1") { layer.msg("操作失敗!", { icon: 2 }); } } }); }
/// <summary> /// 導出Excel /// </summary> /// <returns></returns> public ActionResult ExportExcel() { string json = Request.Params["data"]; try { DataTable dt = ExcelHelper.JsonToDataTable(json); string pathDestop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); ExcelHelper.GridToExcelByNPOI(dt, pathDestop + "\\" + "銷售訂單-" + DateTime.Now.ToString("yyyy-MM-dd") + "導出" + ".xls"); return Content("1"); } catch (Exception) { return Content("-1"); } }
效果圖
導出之后
幫助類貼下面
/// <summary> /// 將json轉換為DataTable /// </summary> /// <param name="strJson">得到的json</param> /// <returns></returns> public static DataTable JsonToDataTable(string strJson) { //轉換json格式 strJson = strJson.Replace(",\"", "*\"").Replace("\":", "\"#").ToString(); //取出表名 var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase); string strName = rg.Match(strJson).Value; DataTable tb = null; //去除表名 strJson = strJson.Substring(strJson.IndexOf("[") + 1); strJson = strJson.Substring(0, strJson.IndexOf("]")); //獲取數據 rg = new Regex(@"(?<={)[^}]+(?=})"); MatchCollection mc = rg.Matches(strJson); for (int i = 0; i < mc.Count; i++) { string strRow = mc[i].Value; string[] strRows = strRow.Split('*'); //創建表 if (tb == null) { tb = new DataTable(); tb.TableName = strName; foreach (string str in strRows) { var dc = new DataColumn(); string[] strCell = str.Split('#'); if (strCell[0].Substring(0, 1) == "\"") { int a = strCell[0].Length; dc.ColumnName = strCell[0].Substring(1, a - 2); } else { dc.ColumnName = strCell[0]; } tb.Columns.Add(dc); } tb.AcceptChanges(); } //增加內容 DataRow dr = tb.NewRow(); for (int r = 0; r < strRows.Length; r++) { try { string a = strRows[r].Split('#')[1].Trim(); if (a.Equals("null")) { dr[r] = ""; } else { dr[r] = strRows[r].Split('#')[1].Trim().Replace(",", ",").Replace(":", ":").Replace("\"", ""); } } catch (Exception e) { throw e; } } tb.Rows.Add(dr); tb.AcceptChanges(); } try { if (tb != null) { return tb; } else { throw new Exception("解析錯誤"); } } catch (Exception e) { throw e; } }
在網上找到一個GridToExcelByNPOI 你們將就用用吧
/// <summary> /// DataTable寫入Excel /// </summary> /// <param name="dt"></param> /// <param name="strExcelFileName"></param> /// <returns></returns> public bool GridToExcelByNPOI(DataTable dt, string strExcelFileName) { try { HSSFWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet("Sheet1"); ICellStyle HeadercellStyle = workbook.CreateCellStyle(); HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; HeadercellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; //字體 NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont(); headerfont.Boldweight = (short)FontBoldWeight.Bold; HeadercellStyle.SetFont(headerfont); //用column name 作為列名 int icolIndex = 0; IRow headerRow = sheet.CreateRow(0); foreach (DataColumn item in dt.Columns) { ICell cell = headerRow.CreateCell(icolIndex); cell.SetCellValue(item.ColumnName); cell.CellStyle = HeadercellStyle; icolIndex++; } ICellStyle cellStyle = workbook.CreateCellStyle(); //為避免日期格式被Excel自動替換,所以設定 format 為 『@』 表示一率當成text來看 cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@"); cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont(); cellfont.Boldweight = (short)FontBoldWeight.Normal; cellStyle.SetFont(cellfont); //建立內容行 int iRowIndex = 1; int iCellIndex = 0; foreach (DataRow Rowitem in dt.Rows) { IRow DataRow = sheet.CreateRow(iRowIndex); foreach (DataColumn Colitem in dt.Columns) { ICell cell = DataRow.CreateCell(iCellIndex); cell.SetCellValue(Rowitem[Colitem].ToString()); cell.CellStyle = cellStyle; iCellIndex++; } iCellIndex = 0; iRowIndex++; } //自適應列寬度 for (int i = 0; i < icolIndex; i++) { sheet.AutoSizeColumn(i); } //寫Excel FileStream file = new FileStream(strExcelFileName, FileMode.OpenOrCreate); workbook.Write(file); file.Flush(); file.Close(); return true; } catch (Exception ex) { return false; } } /// <summary> /// 將excel中的數據導入到DataTable中 /// </summary> /// <param name="fileName">fileName</param> /// <param name="sheetName">excel工作薄sheet的名稱</param> /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param> /// <returns>返回的DataTable</returns> public DataTable ExcelToDataTable(string fileName, string sheetName, bool isFirstRowColumn) { ISheet sheet = null; DataTable data = new DataTable(); IWorkbook workbook = null; FileStream fs = null; int startRow = 0; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(fs); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(fs); if (sheetName != null) { sheet = workbook.GetSheet(sheetName); if (sheet == null) //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet { sheet = workbook.GetSheetAt(0); } } else { sheet = workbook.GetSheetAt(0); } if (sheet != null) { IRow firstRow = sheet.GetRow(0); int cellCount = firstRow.LastCellNum; //一行最后一個cell的編號 即總的列數 if (isFirstRowColumn) { for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { ICell cell = firstRow.GetCell(i); if (cell != null) { string cellValue = cell.StringCellValue; if (cellValue != null) { DataColumn column = new DataColumn(cellValue); data.Columns.Add(column); } } } startRow = sheet.FirstRowNum + 1; } else { startRow = sheet.FirstRowNum; } //最后一列的標號 int rowCount = sheet.LastRowNum; for (int i = startRow; i <= rowCount; ++i) { IRow row = sheet.GetRow(i); if (row == null) continue; //沒有數據的行默認是null DataRow dataRow = data.NewRow(); for (int j = row.FirstCellNum; j < cellCount; ++j) { if (row.GetCell(j) != null) //同理,沒有數據的單元格都默認是null dataRow[j] = row.GetCell(j).ToString(); } data.Rows.Add(dataRow); } } return data; } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); return null; } } ———————————————— 版權聲明:本文為CSDN博主「lbx_15887055073」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。 原文鏈接:https://blog.csdn.net/lbx_15887055073/article/details/82194414
---------------------------------------------------------------------------------------------------------
轉載請記得說明作者和出處哦-.-
作者:KingDuDu
原文出處:https://www.cnblogs.com/kingdudu/articles/4863980.html
---------------------------------------------------------------------------------------------------------