项目需要引用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. 2019-2020-2 20199317《Linux内核原理与分析》第二周作业

    第一章   计算机工作原理 1   存储程序计算机工作模型      存储程序计算机的主要思想是将程序存放在计算机存储器中,然后按存储器中的存储程序的首地址执行程序的第一条指令,以后就按照该程序中编写 ...

  2. springmvc运行流程简单解释(源码解析,文末附自己画的流程图)

    首先看一下DispatcherServlet结构: 观察HandlerExecutionChain对象的创建与赋值,这个方法用来表示执行这个方法的整条链. 进入getHandler方法: 此时的变量h ...

  3. Python面试的一些心得,与Python练习题分享【华为云技术分享】

    版权声明:本文为CSDN博主「华为云」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明.原文链接:https://blog.csdn.net/devcloud/arti ...

  4. 【IoT平台技术对接分享】如何上传正确的消息推送证书

    消息推送应用实现消息推送的接口,部署证书,同时上传根证书到平台. 目前消息推送失败,很大一部分原因是证书上传不对.推荐小伙伴们使用下面的方法导出证书. 推送:平台调用应用服务器的restful接口将数 ...

  5. Redis 中的数据库

    前面我们花了很多的时间介绍了 redis 中基本的数据结构,及其内部的实现情况,这些都是非常基础的东西,可能不经意间你就会用到他们,希望你花点时间了解一下. 接下来,我们将走近 redis 数据库,学 ...

  6. SX1276/SX1278和SXSX1262的详细参数对比

    SX1276/SX1278和SX1262的对比    SX1262是Semtech公司新推出的一款sub-GHz无线收发器.SX1262芯片最大的买点是它的低功耗和超远距离的传输.SX1262接收电流 ...

  7. [TimLinux] TCL 自定义包

    1. 包 很多功能存放在一起,定义为一个包,在iTcl(Incr TCL)之后,可以定义一个类,类可以放在一个包里面,包为一个独立的文件,可以为TCL文件,也可以为C/C++语言实现的动态库. 2. ...

  8. Day 03 Python 基础

    目录 Pycharm 的使用 设置 快捷键 变量 什么是变量 定义变量 变量名的命名规则 变量名的两种命名方式 注释 快捷键(快速注释) 单行注释 多行注释 注释的作用 Turtle库的使用 Pych ...

  9. .Net Core 3.0 以及其前版本编写自定义主机,以允许本机程式(转载)

    像所有的托管代码一样,.NET Core 应用程序也由主机执行. 主机负责启动运行时(包括 JIT 和垃圾回收器等组件)和调用托管的入口点. 托管 .NET Core 运行时是高级方案,在大多数情况下 ...

  10. .net下DllImport的一个小问题

    最近搞几个PInvoke几个DLL, 在.net 2.0下木有问题, 跑的很好 如下: [DllImport( "tjo.dll" )] private static extern ...