this.listLoading = true GetInfoToExcel(this.QueryParams).then(res => { this.listLoading = false const content = res const blob = new Blob([content]) const fileName = '统计.xls' if ('download' in document.createElement('a')) { // 非IE下载 const elink = document.createElement('a') elink.download = fileName elink.style.display = 'none' elink.href = URL.createObjectURL(blob) document.body.appendChild(elink) elink.click() URL.revokeObjectURL(elink.href) // 释放URL 对象 document.body.removeChild(elink) } else { // IE10+下载 navigator.msSaveBlob(blob, fileName)

1.3 API定义  axios

responseType: 'blob', 属性最为关键,如果没有设置下载的文件将出现如下报错

Microsoft Excel
"xxxx.xls"的文件格式和扩展名不匹配。文件可能已损坏或不安全。除非您信任其来源,否则请勿打开。是否仍要打开它?
export function GetInfoToExcel(data) {
  return request({
    url: '/api/v1/xls/GetInfoToExcel',
    method: 'post',
    responseType: 'blob',

二、ASP.NET WEB API后端

2.1 api路由接口

public class V1PresController : ApiController
   [AuthFilterOutside]
   [HttpPost]
   [Route("api/v1/xls/GetInfoToExcel")]
   public async Task<IHttpActionResult> GetInfoToExcel([FromBody]GetInfoRequest jsonText)
           jsonText.CurPage = 1;
           jsonText.PageSize = 9999999;
           List<xlsInfo> list = (await Task.WhenAll(API.GetxlsInfo(jsonText, HttpContext.Current)))[0].list;
           byte[] info = list.ToExcelBytes(xlsInfo.TITLES, xlsInfo.SHEETNAME);
           return ResponseFileExcel(info);
        catch
            return Ok();

2.2、从数据获取数据,类型为 List<T>

public async Task<GetxlsInfoResponse> GetxlsInfo(GetlxsInfoRequest request, HttpContext httpContext)
            GetxlsInfoResponse res = new GetxlsInfoResponse();
            res.Success();
                using (ssddsEntities db = new ssddsEntities())
                    string sqlFormat = "{0} prescription {1} Order By create_time {2}";
                    string sqlwhere = "";
                    sqlwhere = string.Format(" WHERE create_time {0}",request.BT);
                    if(request.machine_id != 0)
                        sqlwhere += string.Format(" AND fetch_window = '{0}'", request.machine_id);
                    string sqlCount = string.Format(sqlFormat, request.SELECTALL,sqlwhere,"");
                    List<prescription> listSrc = await db.Database.SqlQuery<prescription>(sqlCount).ToListAsync();
                    //List<sys_code> sysCodes = await SCGroupCode.machine_type.GetSysCodes();
                    //List<sys_unit> sysUnits = PublicMysql.GetSysUnits();
                    var query = listSrc.GroupBy(o => o.create_time.Date).OrderBy(o=>o.Key);
                    List<PresInfo> Infos = new List<PresInfo>();
                    foreach (var item in query)
                        int nE = item.Where(o => o.pre_state == 2).Count();
                        int nN = item.Where(o => o.pre_state == 1).Count();
                        int nT = item.Count();
                        string sR = (nN + nE) == 0 ?"0.00%" : string.Format("{0}%", ((float)nE*100.0F / (float)(nN + nE)).ToString("0.00"));
                        PresInfo Info = new PresInfo()
                            date = item.Key.ToString(Global.DATE),
                            num_total = nT,
                            num_error = nE,
                            num_normal = nN,
                            rate = sR
                        Infos.Add(Info);
                    res.list = Infos.ToPageList(request.CurPage,request.PageSize);
                    res.count = Infos.Count;
                return res;
            catch (Exception ex)
                log.Error("GetUserInfo 异常" + ex.Message);
                res.Exception(ex);
                return res;

2.3、将List<T> 通过NPOI第三方Excel库转化为 Byte []数组 

注意:NOPI的工作薄名称规则应该适应Excel文件的命名规则,工作薄名称不能使用,冒号:,中括号[],斜杠\等符号,否侧将出现以下报错,或其他未知错误。

发现“xxx.xls”中的部分内容有问题。是否让我们尽量尝试恢复?如果您信任此工作薄的源,请单机“是”。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
namespace RSS_SSDDS.API.BIZ
    /// <summary>
    /// </summary>
    public static class PublicExcel
        /// <summary>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <param name="titles"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public static byte[] ToExcelBytes<T>(this List<T> data,Dictionary<string,string> titles,string sheetName)
                HSSFWorkbook workbook = new HSSFWorkbook(); // 工作簿
                ExcelAddRow(titles, data, sheetName, ref workbook);
                using ( MemoryStream ms = new MemoryStream())
                    workbook.Write(ms);
                    byte[] info = ms.ToArray();
                    workbook.Close();
                    return info;
            catch(Exception exp)
            return null;
        /// <summary>
        /// </summary>
        public static void ExcelAddRow<T>(Dictionary<string, string> cellHeard, List<T> enList, string sheetName, ref HSSFWorkbook workbook)
                ISheet sheet = workbook.CreateSheet(sheetName); // 工作表
                IRow row = sheet.CreateRow(0);
                List<string> keys = cellHeard.Keys.ToList();
                for (int i = 0; i < keys.Count; i++)
                    row.CreateCell(i).SetCellValue(cellHeard[keys[i]]); // 列名为Key的值
                // 3.List对象的值赋值到Excel的单元格里
                int rowIndex = 1; // 从第二行开始赋值(第一行已设置为单元头)
                foreach (var en in enList)
                    IRow rowTmp = sheet.CreateRow(rowIndex);
                    for (int i = 0; i < keys.Count; i++) // 根据指定的属性名称,获取对象指定属性的值
                        string cellValue = ""; // 单元格的值
                        object properotyValue = null; // 属性的值
                        System.Reflection.PropertyInfo properotyInfo = null; // 属性的信息
                        // 3.1 若属性头的名称包含'.',就表示是子类里的属性,那么就要遍历子类,eg:UserEn.UserName
                        if (keys[i].IndexOf(".") >= 0)
                            // 3.1.1 解析子类属性(这里只解析1层子类,多层子类未处理)
                            string[] properotyArray = keys[i].Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
                            string subClassName = properotyArray[0]; // '.'前面的为子类的名称
                            string subClassProperotyName = properotyArray[1]; // '.'后面的为子类的属性名称
                            System.Reflection.PropertyInfo subClassInfo = en.GetType().GetProperty(subClassName); // 获取子类的类型
                            if (subClassInfo != null)
                                // 3.1.2 获取子类的实例
                                var subClassEn = en.GetType().GetProperty(subClassName).GetValue(en, null);
                                // 3.1.3 根据属性名称获取子类里的属性类型
                                properotyInfo = subClassInfo.PropertyType.GetProperty(subClassProperotyName);
                                if (properotyInfo != null)
                                    properotyValue = properotyInfo.GetValue(subClassEn, null); // 获取子类属性的值
                            // 3.2 若不是子类的属性,直接根据属性名称获取对象对应的属性
                            properotyInfo = en.GetType().GetProperty(keys[i]);
                            if (properotyInfo != null)
                                properotyValue = properotyInfo.GetValue(en, null);
                        // 3.3 属性值经过转换赋值给单元格值
                        if (properotyValue != null)
                            cellValue = properotyValue.ToString();
                            // 3.3.1 对时间初始值赋值为空
                            if (cellValue.Trim() == "0001/1/1 0:00:00" || cellValue.Trim() == "0001/1/1 23:59:59")
                                cellValue = string.Empty;
                        // 3.4 填充到Excel的单元格里
                        rowTmp.CreateCell(i).SetCellValue(cellValue);
                    rowIndex++;
            catch (Exception) { }

 2.4、将Byte[] 数组回传给前端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http.Results;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.IO;
using RSS_SSDDS.API.OAuth;
using RSS_SSDDS.API.Models;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Net.Http.Headers;
using System.Web.Http.Results;
namespace RSS_SSDDS.API.Controllers.V1
    /// <summary>
    /// 基础控制器
    /// </summary>
    public class BaseController: ApiController
        log4net.ILog log = log4net.LogManager.GetLogger(typeof(BaseController));
        /// <summary>
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public ResponseMessageResult ResponseFileExcel(byte[] data)
            var browser = String.Empty;
            if (HttpContext.Current.Request.UserAgent != null)
                browser = HttpContext.Current.Request.UserAgent.ToUpper();
            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
            Stream stream = new MemoryStream(data);
            httpResponseMessage.Content = new StreamContent(stream);
            httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            httpResponseMessage.Content.Headers.ContentType.CharSet= "utf8";
            httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                FileName =
                    browser.Contains("FIREFOX")
                        ? Path.GetFileName("test.xlsx")
                        : HttpUtility.UrlEncode(Path.GetFileName("test.xls"))
            return ResponseMessage(httpResponseMessage);
        /// <summary>
        /// 获取当前用户编号
        /// </summary>
        /// <returns></returns>
        public async Task<int> getuid()
                HttpContextBase Content = (HttpContextBase)Request.Properties["MS_HttpContext"];
                var token = Content.Request.Headers["Token"];
                return await ValidateTicket(token.ToString());
            catch (Exception ex)
                log.Err(ex);
                return -1;
        /// <summary>
        /// </summary>
        public async Task<int> ValidateTicket(string encryptToken)
            int uid = -1;
                using (ssddsEntities db = new ssddsEntities())
                    var temp = await db.sys_ticketauth.Where(m => m.token.Equals(encryptToken) && m.state == 1).ToListAsync();
                    int count = temp.Count();
                    if (count > 0)
                        uid = temp.FirstOrDefault().user_id.Value;
            catch (Exception ex)
                log.Err(ex);
            return uid;
                    一、VUE前端1.1、元素定义元素使用 element 控件&lt;el-button type="info" plain size="medium " @click="exportExcel"&gt;&lt;i class="el-icon-edit el-icon--left" /&gt;导出Excel&lt;/el-button&gt;1.2、事件定义import { GetInfoToExcel } from '@/api/xlsInfo' methods: {
					你要明白,任何问题都不是孤立存在的,一定有人曾经遇到过,并且已经有更好的解决办法了,只是我还不知道。我不应该在黑暗中独自前行,去重新发明轮子,也许我的顿悟,只是别人的基本功!我应该要站在巨人的肩膀上,学习更成熟的经验和方法,然后再来解决这个问题
					02-21
使用起来也很简单,我们构造 ExcelHelper 类,并在controller里面使用。
比如 person类有 id,name,age 3个属性,则 在controller里面这样调用
[Route("ExportExcel")]
[HttpGet]
public IActionRes...
				
后台返回文件流 1.因为是文件下载,所以在取后台数据的时候,要多传递一个【responseType: ‘blob’】这个参数,是为了最后数据返回时response的data为【blob】文件格式(data: Blob {size: 22528, type: “application/vnd.ms-excel”}),否则返回的数据只有文件流的结构体,不包含【blob】。 下面为封装的获取后台文件流...
很久之前记录了一篇vue导出模板的功能,vue导出模板下载 https://blog.csdn.net/weixin_42416812/article/details/103863501 这个需要提供一个模板文件,然后存在前端,最后再导出。 今天补充下,后端返回一个文件流的接口,怎么导出element-ui的表格文件 <el-button type="success" size="mini" icon="el-icon-download"
ASP.NET服务器端导出数据到Excelweb项目使用过html的拼接成table表格的形式导出数据到excel,但是导出execl表格不能直接修改和保存,存在数据丢失的情况,采用这种文件流的形式就不会出现excel表不能修改的情况了。 解决方案中需要引用的类库如下: ICSharpCode.SharpZipLib.dll NPOI.dll NPOI.OOXML.dll NPOI.OpenXml
关于如果正确是用NPOI其实有一点很重要,因为是涉及前端的交互那么就需要前端传过来的文件进行识别判断存储操作,存储好了之后必然会获得到一个数据那就是文件存储的excel位置,这个很重要。 接下来进入正文,如何使用NPOI进行excel的批量的导入导出操作,首先安装NPOI的dll文件,百度有很多教程,自己动手。 前面已经总结了如果进行文件的存储判断等,现在就是进入批量导入数据库 using NPO...
个人觉得轻简级的ORM既要支持强类型编码,又要有执行效率,还要通俗易懂给开发者友好提示,结合Expression可轻松定制自己所需要功能。 Orm成品开源项目地址https://github.com/PlugNT/util6 表达式解析类: 1 using System; 2 using System.Collections; 3 using Sys...
【数据库-MySql】2013 - Lost connection to MySQL server at reading initial communication packet 阿森的经验宝箱: 方法一 成功解决 方法二 没用 【 IntelliJ IDEA】Error: Module not Specified 在“Use classpath of module:”下拉选项卡中选择需要运行的 Module (模块). 【 IntelliJ IDEA】Error: Module not Specified 都一次遇到这种情况,博主的这个方法是有用的。 【语言-C#】[Description(""), Browsable(true), Category("")] Scarlett2025: [Description(""), Browsable(true), Category("二维表头")]这是一种注释吗