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);
                })
        })
    };
  • 相关阅读:
    C++调用Java的Jar包(带参数)
    SOA创建Form表单
    vs2013 IntelliSense: "const char *" 类型的实参与 "LPCWSTR" 类型的形参不兼容
    idea无法正常使用SVN的解决方法
    关于C语言中print输出问题
    TC怎么在代码中实现选中一个TCCcomponent对象?
    Unity 1.0 中文文档:1 Unity 简介
    Unity(四):使用场景Ⅰ:建立类型映射
    这个世界上没有白干的活
    Unity(三):快速入门
  • 原文地址:https://www.cnblogs.com/liuqiyun/p/10729904.html
Copyright © 2011-2022 走看看