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);
                })
        })
    };
  • 相关阅读:
    进程调度算法
    附近的人,附近的卖家(geohash+前缀树)
    海量信息库,查找是否存在(bloom filter布隆过滤器)
    继承、虚继承和虚函数表对类的大小的影响
    linux 用户空间与内核空间——高端内存详解
    0-1背包问题入门
    范式
    vue的无缝滚动插件vue-seamless-scroll的安装与使用
    在vue项目中使用swiper2.7.6
    vue项目在IE下报 [vuex] vuex requires a Promise polyfill in this browser问题
  • 原文地址:https://www.cnblogs.com/liuqiyun/p/10729904.html
Copyright © 2011-2022 走看看