前端代碼:
<script type="text/javascript"> function downLoad(){ var blob = this.dataURLtoBlob("這里放字節流字符串"); var downloadUrl = window.URL.createObjectURL(blob); var anchor = document.createElement("a"); anchor.href = downloadUrl; anchor.download = decodeURI(""); anchor.click(); } function dataURLtoBlob(base64Str) { var bstr = atob(base64Str), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } // 下載的是excel格式的文件 return new Blob([u8arr], { type: "application/vnd.ms-excel" }); } </script>
后端方法:
using Aspose.Cells
/// <summary> /// 讀取模板並寫入數據-文件流 /// </summary> /// <param name="paramsData"></param> /// <returns></returns> public virtual string GetAssetPackInfoFile(InputZcSyQueryDto paramsData) { List<AssetPackReturnResultDto> list = GetAssetPackInfoList(paramsData); string templateFullPath = ImportConst.WAssetPackExcelImport; //模板路徑 //輸出文件 using (FileStream file = new FileStream(templateFullPath, FileMode.Open)) { Workbook workbook = new Workbook(file); Worksheet ws = workbook.Worksheets[0]; //將list數據寫入excel for (int i = 0; i < list.Count; i++) { var currentRow = list[i]; WriteCellData(ws, i + 1, 0, currentRow.Name); WriteCellData(ws, i + 1, 1, currentRow.Time); WriteCellData(ws, i + 1, 2, currentRow.Ztze); WriteCellData(ws, i + 1, 3, currentRow.Mwysr); WriteCellData(ws, i + 1, 4, currentRow.Lce); WriteCellData(ws, i + 1, 5, currentRow.Jwysr); WriteCellData(ws, i + 1, 6, currentRow.Xmfg); WriteCellData(ws, i + 1, 7, currentRow.Hbl); } MemoryStream ms = workbook.SaveToStream(); var buffer = new byte[ms.Length]; ms.Position = 0; ms.Read(buffer, 0, (int)ms.Length); ms.Flush(); ms.Close(); return Convert.ToBase64String(buffer); } }
公共方法:
/// <summary> /// 向excel中單元格寫入數據 /// </summary> /// <param name="dataSheet">數據工作表</param> /// <param name="rowIndex">行</param> /// <param name="cellIndex">列</param> /// <param name="value">值</param> private void WriteCellData(Worksheet dataSheet, int rowIndex, int cellIndex, object value) { //獲取單元格 var cell = dataSheet.Cells[rowIndex, cellIndex]; cell.PutValue(value.ToString(), true); }
獲取模板:
public static readonly string WAssetPackExcelImport = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Customize\App_Data\Zgxt\Xxpl\ExcelConfig\XXX.xlsx");