项目需要引用NPOI的Nuget包:DotNetCore.NPOI-v1.2.2

A-前端触发下载Excel的方法有三种:

  1-JS-Url跳转请求-后台需要返回文件流数据:

window.Location.href = "/ajax/toolhelper.js?action=reBuyExport&beginTime=" + beginTime + "&endTime=" + endTime;

  2-使用form+iframe请求文件流-后台需要返回文件流数据:

<form target="downLoadIframe" method="post" action="/ajax/toolhelper.js?action=reBuyExport">
<div class="form-group">
<label for="datetime">beginTime:</label>
<input type="date" class="form-control" name="beginTime" placeholder="Enter beginTime" />
</div>
<div class="form-group">
<label for="datetime">endTime:</label>
<input type="date" class="form-control" name="endTime" placeholder="Enter endTime">
</div>
<button type="submit" class="btn btn-primary" id="btnExport">导出Excel</button>
</form>
<iframe id="downLoadIframe" name="downLoadIframe" style="display:none;"></iframe>

  3-JS-Fetch请求使用Blob保存二进制文件流数据,通过A标签下载流文件-后台需要返回文件流数据:

  领导推荐这种方法,经过检验的,可以应对大文件下载的超时问题

fetch(url).then(function (res) {
res.blob().then(function (blob) {
var a = document.createElement('a');
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
});
});

B-后台返回流数据:

Core下的Excel帮助类

/// <summary>
/// EXCEL帮助类
/// </summary>
/// <typeparam name="T">泛型类</typeparam>
/// <typeparam name="TCollection">泛型类集合</typeparam>
public class ExcelHelp<T, TCollection> where TCollection : List<T> where T : new()
{
public static ExcelHelp<T, TCollection> INSTANCE = new ExcelHelp<T, TCollection>();
//获取httpResponse对象原位置,放在这里不知道会报错:服务器无法在发送 HTTP 标头之后追加标头
//可能是这里拿到的httpResponse对象不是最新请求的对象导致的,将其放到方法内部即可
//HttpResponse baseResponse = HttpContext.Current.Response; /// <summary>
/// 将数据导出EXCEL
/// </summary>
/// <param name="tList">要导出的数据集</param>
/// <param name="fieldNameAndShowNameDic">键值对集合(键:字段名,值:显示名称)</param>
/// <param name="httpResponse">响应</param>
/// <param name="excelName">文件名(必须是英文或数字)</param>
/// <returns></returns>
public async Task ExportExcelData(TCollection tList, Dictionary<string, string> fieldNameAndShowNameDic, HttpResponse httpResponse, string excelName = "exportResult")
{
IWorkbook workbook = new HSSFWorkbook();
ISheet worksheet = workbook.CreateSheet("sheet1"); List<string> columnNameList = fieldNameAndShowNameDic.Values.ToList();
//设置首列显示
IRow row1 = worksheet.CreateRow();
ICell cell = null;
ICellStyle cellHeadStyle = workbook.CreateCellStyle();
//设置首行字体加粗
IFont font = workbook.CreateFont();
font.Boldweight = short.MaxValue;
cellHeadStyle.SetFont(font);
for (var i = ; i < columnNameList.Count; i++)
{
cell = row1.CreateCell(i);
cell.SetCellValue(columnNameList[i]);
cell.CellStyle = cellHeadStyle;
} //根据反射创建其他行数据
var raws = tList.Count;
Dictionary<int, PropertyInfo> indexPropertyDic = this.GetIndexPropertyDic(fieldNameAndShowNameDic.Keys.ToList()); for (int i = ; i < raws; i++)
{
row1 = worksheet.CreateRow(i + ); for (int j = ; j < fieldNameAndShowNameDic.Count; j++)
{
cell = row1.CreateCell(j);
if (indexPropertyDic[j].PropertyType == typeof(int)
|| indexPropertyDic[j].PropertyType == typeof(decimal)
|| indexPropertyDic[j].PropertyType == typeof(double))
{
cell.SetCellValue(Convert.ToDouble(indexPropertyDic[j].GetValue(tList[i])));
}
else if (indexPropertyDic[j].PropertyType == typeof(DateTime))
{
cell.SetCellValue(Convert.ToDateTime(indexPropertyDic[j].GetValue(tList[i]).ToString()));
}
else if (indexPropertyDic[j].PropertyType == typeof(bool))
{
cell.SetCellValue(Convert.ToBoolean(indexPropertyDic[j].GetValue(tList[i]).ToString()));
}
else
{
cell.SetCellValue(indexPropertyDic[j].GetValue(tList[i]).ToString());
}
}
//设置行宽度自适应
worksheet.AutoSizeColumn(i, true);
} //对于.xls文件
//application/vnd.ms-excel
//用于.xlsx文件。
//application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue("application/vnd.ms-excel");
mediaType.Encoding = System.Text.Encoding.UTF8; httpResponse.ContentType = mediaType.ToString();
//设置导出文件名
httpResponse.Headers.Add("content-disposition", $"attachment;filename={excelName}.xls");
MemoryStream ms = new MemoryStream();
//这句代码非常重要,如果不加,会报:打开的EXCEL格式与扩展名指定的格式不一致
ms.Seek(, SeekOrigin.Begin);
workbook.Write(ms);
byte[] myByteArray = ms.GetBuffer();
httpResponse.Headers.Add("Content-Length", myByteArray.Length.ToString());
await httpResponse.Body.WriteAsync(myByteArray, , myByteArray.Length);
} /// <summary>
/// 根据属性名顺序获取对应的属性对象
/// </summary>
/// <param name="fieldNameList"></param>
/// <returns></returns>
private Dictionary<int, PropertyInfo> GetIndexPropertyDic(List<string> fieldNameList)
{
Dictionary<int, PropertyInfo> indexPropertyDic = new Dictionary<int, PropertyInfo>(fieldNameList.Count);
List<PropertyInfo> tPropertyInfoList = typeof(T).GetProperties().ToList();
PropertyInfo propertyInfo = null;
for (int i = ; i < fieldNameList.Count; i++)
{
propertyInfo = tPropertyInfoList.Find(m => m.Name.Equals(fieldNameList[i], StringComparison.OrdinalIgnoreCase));
indexPropertyDic.Add(i, propertyInfo);
} return indexPropertyDic;
} }

Core的中间件请求方法:

TBDataHelper为提前注入的数据库帮助类,需要改成自己的数据请求类;

自定义的导出文件名,不能输入中文,暂时还没有找到解决办法;

BaseMiddleware为基类,切记基类中只能存常态化的数据,如:下一中间件,配置,缓存。不能存放Request,Response等!!!

public class ToolHelperMiddleware : BaseMiddleware
{
public TBDataHelper TBDataHelper { get; set; }
public ToolHelperMiddleware(RequestDelegate next, ConfigurationManager configurationManager, IMemoryCache memoryCache, TBDataHelper tBDataHelper) : base(next, configurationManager, memoryCache)
{
this.TBDataHelper = tBDataHelper;
} public async Task Invoke(HttpContext httpContext)
{
var query = httpContext.Request.Query;
var queryAction = query["action"]; switch (queryAction)
{
case "reBuyExport":
await this.ReBuyExport(httpContext);
break;
}
} /// <summary>
/// 复购数据导出
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
private async Task ReBuyExport(HttpContext httpContext)
{
var request = httpContext.Request;
var response = httpContext.Response;
var requestForm = request.Form; try
{
DateTime beginTime = Convert.ToDateTime(requestForm["beginTime"]);
DateTime endTime = Convert.ToDateTime(requestForm["endTime"]); List<RebuyModel> rebuyModelList = this.TBDataHelper.SelectReBuyList(beginTime, endTime); Dictionary<string, string> fieldNameAndShowNameDic = new Dictionary<string, string>();
fieldNameAndShowNameDic.Add("UserID", "用户ID");
fieldNameAndShowNameDic.Add("PayCount", "支付数");
fieldNameAndShowNameDic.Add("BeforeBuyCount", beginTime.ToString("MM/dd") + "之前支付数"); string fileName = $"{beginTime.ToString("MMdd")}_{endTime.ToString("MMdd")}ReBuyExport_{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}";
await ExcelHelp<RebuyModel, List<RebuyModel>>.INSTANCE.ExportExcelData(rebuyModelList, fieldNameAndShowNameDic, response, fileName);
}
catch (Exception e)
{
throw e;
}
} }
/// <summary>
/// 中间件基类
/// </summary>
public abstract class BaseMiddleware
{
/// <summary>
/// 等同于ASP.NET里面的WebCache(HttpRuntime.Cache)
/// </summary>
protected IMemoryCache MemoryCache { get; set; } /// <summary>
/// 获取配置文件里面的配置内容
/// </summary>
protected ConfigurationManager ConfigurationManager { get; set; } /// <summary>
/// 下一个中间件
/// </summary>
protected RequestDelegate Next { get; set; } public BaseMiddleware(RequestDelegate next, params object[] @params)
{
this.Next = next;
foreach (var item in @params)
{
if (item is IMemoryCache)
{
this.MemoryCache = (IMemoryCache)item;
}
else if (item is ConfigurationManager)
{
this.ConfigurationManager = (ConfigurationManager)item;
}
}
} }

C#_.NetCore_Web项目_EXCEL数据导出(ExcelHelper_第一版)的更多相关文章

  1. C#_.NetFramework_WebAPI项目_EXCEL数据导出

    [推荐阅读我的最新的Core版文章,是最全的介绍:C#_.NetCore_Web项目_EXCEL数据导出] 项目需要引用NPOI的Nuget包: A-2--EXCEL数据导出--WebAPI项目--N ...

  2. C#_.NetFramework_Web项目_EXCEL数据导出

    [推荐阅读我的最新的Core版文章,是最全的介绍:C#_.NetCore_Web项目_EXCEL数据导出] 项目需引用NPOI的NuGet包: A-2:EXCEL数据导出--Web项目--C#代码导出 ...

  3. C#_.NetCore_WebAPI项目_EXCEL数据导出(ExcelHelper_第二版_优化逻辑)

    项目需要引用NPOI的Nuget包:DotNetCore.NPOI-v1.2.2 本篇文章是对WebAPI项目使用NPOI操作Excel时的帮助类:ExcelHelper的改进优化做下记录: 备注:下 ...

  4. C#_.NetFramework_Web项目_EXCEL数据导入

    [推荐阅读我的最新的Core版文章,是最全的介绍:C#_.NetCore_Web项目_EXCEL数据导出] 需要引用NPOI的Nuget包:NPOI-v2.4.1 B-1:EXCEL数据导入--C#获 ...

  5. C#_.NetFramework_Web项目_NPOI_EXCEL数据导入

    [推荐阅读我的最新的Core版文章,是最全的介绍:C#_.NetCore_Web项目_EXCEL数据导出] 项目需要引用NPOI的Nuget包: B-2--EXCEL数据导入--NPOI--C#获取数 ...

  6. 【基于WinForm+Access局域网共享数据库的项目总结】之篇二:WinForm开发扇形图统计和Excel数据导出

    篇一:WinForm开发总体概述与技术实现 篇二:WinForm开发扇形图统计和Excel数据导出 篇三:Access远程连接数据库和窗体打包部署 [小记]:最近基于WinForm+Access数据库 ...

  7. DB数据导出工具分享

    一个根据数据库链接字符串,sql语句 即可将结果集导出到Excel的工具 分享,支持sqlserver,mysql. 前因 一个月前朋友找到我,让我帮忙做一个根据sql导出查询结果到Excel的工具( ...

  8. .Net之Nopi Excel数据导出和批量导入功能

    一.介绍NPOI和编写demo的原因 1.Npoi是什么: 它是一个专门用于读写Microsoft Office二进制和OOXML文件格式的.NET库,我们使用它能够轻松的实现对应数据的导入,导出功能 ...

  9. asp.net 将repeater上数据导出到excel

    1,首先得到一个DataTable public DataTable GetTable(string sql) { SqlConnnection con=new SqlConnection(Confi ...

随机推荐

  1. php踩过的那些坑(4) false,NULL,0,''详解

    一.前方有坑 php开发过程中,难免会遇到这四个值:false,null,0,’',并且也会对这四个值进行比较,然后分别进行业务代码处理.一招不慎,就会踩到坑,影响数据判断的正确性和安全性,以至于造成 ...

  2. Netty学习——通过websocket编程实现基于长连接的双攻的通信

    Netty学习(一)基于长连接的双攻的通信,通过websocket编程实现 效果图,客户端和服务器端建立起长连接,客户端发送请求,服务器端响应 但是目前缺少心跳,如果两个建立起来的连接,一个断网之后, ...

  3. 2019-2020-1 20199304《Linux内核原理与分析》第五周作业

    第四章 系统调用的三层机制(上) 4.1 用户态.内核态和中断 知识点总结: 与系统调用打交道的方式是通过库函数的方式. 用户态与内核态的区分 内核态:高的执行级别下,代码可以执行特权指令,访问任意的 ...

  4. 基于Win服务的标签打印(模板套打)

    最近做了几个项目,都有在产品贴标的需求 基本就是有个证卡类打印机,然后把产品的信息打印在标签上. 然后通过机器人把标签贴到产品上面 标签信息包括文本,二维码,条形码之类的,要根据对应的数据生成二维码, ...

  5. 【Python成长之路】python 基础篇 -- global/nonlocal关键字使用

    1 课程起源 有一次在工作中编写python工具时,遇到一个 问题:从配置文件读取变量A后,无法在内存中把A的值改变成新的内容.为了解决"更新内存中变量"的这个问题,查找了一些帖子 ...

  6. [Mathematics][BJTU][Calculus]Detailed explanations and proofs of the Dirac-Abel Discriminant Methods which deal with the conditional convergence

    So, today we will talk about the conditional convergence and two discriminant methods, namely Dirac- ...

  7. Vue全家桶高仿小米商城

    大家好,我是河畔一角,时隔半年再次给大家带来一门重量级的实战课程:<Vue全家桶高仿小米商城>,现在很多公司都在参与到商城的构建体系当中,因此掌握一套商城的标准开发体系非常重要:商城的开始 ...

  8. 带你从头到尾捋一遍MySQL索引结构(2)

    前言 Hello我又来了,快年底了,作为一个有抱负的码农,我想给自己攒一个年终总结.索性这次把数据库中最核心的也是最难搞懂的内容,也就是索引,分享给大家. 这篇博客我会谈谈对于索引结构我自己的看法,以 ...

  9. python数据结构——单向链表

    链表 ( Linked List ) 定义:由许多相同数据类型的数据项按照特定顺序排列而成的线性表. 特点:各个数据在计算机中是随机存放且不连续. 优点:数据的增删改查都很方便,当有新的数据加入的时候 ...

  10. 一次使用pip后的总结

    pip 常用命令及搭配操作 一 .当安装了多个版本python的时候,表示用pythonx 的pip 进行: 1.pythonx -m pip install + 包名 装 包 2.pythonx - ...