zoukankan      html  css  js  c++  java
  • mvc 根据模板导出excel,直接导出文件流

    1.c#

    /// <summary>
            /// 导出员工
            /// </summary>
            /// <returns></returns>
            [HttpGet]
            public FileResult ExportEmployee()
            {
                var eid = getEnterpriseId();
    
                LogWriter.ToDebug($"导出员工开始");
    
                string templateUrl = "/ExportFile/Template/ExportEmployeesTemplate.xls";
                //string temporaryUrl = $"/ExportFile/Temporary/ExportEmployees_{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}.xls";
    
                string templateRealUrl = Request.MapPath(templateUrl);
                //string temporaryRealUrl = Request.MapPath(temporaryUrl);
    
                //System.IO.File.Copy(templateRealUrl, temporaryRealUrl, true);
                var result = ExportEmployees(eid, templateRealUrl);
    
    
                LogWriter.ToDebug($"导出员工结束");
                return result; //return Json(new ResultInfo(1001, "导出员工失败"));
    
            }
    private FileResult ExportEmployees(Guid eId, string tempFileUrl)
            {
                var employeesList = EnterpriseBLL.GetExportEmployees(eId);
                IWorkbook workbook;
                try
                {
                    using (FileStream stream = System.IO.File.Open(tempFileUrl, FileMode.Open, FileAccess.Read))
                    {
                        workbook = new HSSFWorkbook(stream);
                        ISheet sheet = workbook.GetSheet("Sheet1");
                        for (int i = 0; i < employeesList.Count; i++)
                        {
                            IRow row = sheet.CreateRow(i + 3);
                            for (int j = 0; j < 7; j++)
                            {
                                ICell cell = row.CreateCell(j);
                                cell.SetCellValue(EnterpriseBLL.getCellValue(employeesList[i], j));
                            }
                        }
    
                    }
                    //转为字节数组  
                    NpoiMemoryStream streamOut = new NpoiMemoryStream();
                    streamOut.AllowClose = false;
                    workbook.Write(streamOut);
                    streamOut.Seek(0, SeekOrigin.Begin);
                    //return File(stream, "application/vnd.ms-excel", file);
                    return File(streamOut, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Employees.xls");
    
                }
                catch (Exception ex)
                {
                    LogWriter.ToError($"ZJCX.ZJCDPC.WebUI->EnterpriseBLL->ExportEmployees内部错误,{ex.Message}", ex);
                    throw ex;
                }
            }
            //新建类 重写Npoi流方法
            public class NpoiMemoryStream : MemoryStream
            {
                public NpoiMemoryStream()
                {
                    AllowClose = true;
                }
    
                public bool AllowClose { get; set; }
    
                public override void Close()
                {
                    if (AllowClose)
                        base.Close();
                }
            }

    前端:

    通过创建a标签实现重命名文件

    this.$getDownload('/API/ExportEmployee').then(res => {
                        let blob = new Blob([res.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheethml.sheet" });
                        let objctUrl = URL.createObjectURL(blob);
    
                        var a = document.createElement('a');
                        a.innerHTML = "员工信息.xls";
                        a.download = "员工信息.xls";
                        a.href = objctUrl;
                        document.body.appendChild(a);
    
                        var evt = document.createEvent("MouseEvents");
                        evt.initEvent("click", false, false);
                        a.dispatchEvent(evt);
                        document.body.removeChild(a);
                    })

    前端用的vue-anxio,需要注意:

    //get请求封装
    export function getDownload(url) {
        return new Promise((resolve, reject) => {
    
            axios({
                method: 'get',
                url: baseUrl+url,
                responseType: 'arraybuffer'
            }).then(res => {
                resolve(res)
                }, err => {
                    console.log('get 报错');
                    reject(err);
                })
        })
    };
  • 相关阅读:
    BZOJ2821 作诗(Poetize) 【分块】
    BZOJ2724 蒲公英 【分块】
    Codeforces 17E Palisection 【Manacher】
    BZOJ2565 最长双回文串 【Manacher】
    Codeforces 25E Test 【Hash】
    CODEVS3013 单词背诵 【Hash】【MAP】
    HDU2825 Wireless Password 【AC自动机】【状压DP】
    HDU2896 病毒侵袭 【AC自动机】
    HDU3065 病毒侵袭持续中【AC自动机】
    HDU2222 Keywords Search 【AC自动机】
  • 原文地址:https://www.cnblogs.com/liuqiyun/p/10729904.html
Copyright © 2011-2022 走看看