前端代码:
<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, @"CustomizeApp_DatagxtXxplExcelConfigXXX.xlsx");