ASP.NET使用DotNetZip+CsvHelper将多个CSV文件放入一个ZIP中并下载
- 需求说明
查询数据库中的一张表里面的数据,数据量可能有100万+,将查询出的数据生成Excel并进行下载。
- 存在的问题
Excel2007之后的版本最大行数为1048576,当数据量超过这个数值时,将会无法显示全部数据。
- 实现方案
通过拆分为多个文件的方式,打包成一个ZIP包进行下载。
- 样例代码
- 引用Nuget包
DotNetZip
CsvHelper - using namespace
using Ionic.Zip; using CsvHelper;
- 案例
using Microsoft.AspNetCore.Mvc; using Ionic.Zip; using CsvHelper; using System.Text; using System.Globalization; using WebApplication1.Entities; namespace WebApplication1.Controllers { public class DownloadController : Controller { public IActionResult Index() { return View(); } [HttpGet] public IActionResult GetZIP() { //模拟访问数据库查询出很多条数据。 var irrList = new List<ExIRR>(); for (int i = 0; i < 600000; i++) { irrList.Add(new ExIRR() { BondId = Guid.NewGuid().ToString(), BondName = $"123-{i}", CDate = DateTime.Now, Plate = "板块", TableName = "TF_TEST", AmountType = "其他公司费用", Amount = i }); } //构建第一个CSV var stream = new MemoryStream(); var streamWriter = new StreamWriter(stream, Encoding.UTF8); var csv = new CsvWriter(streamWriter, CultureInfo.InvariantCulture); csv.WriteHeader<ExIRR>(); csv.NextRecord(); foreach (var record in irrList) { csv.WriteRecord(record); csv.NextRecord(); } csv.Flush(); stream.Position = 0; //构建第二个CSV var stream2 = new MemoryStream(); var streamWriter2 = new StreamWriter(stream2, Encoding.UTF8); var csv2 = new CsvWriter(streamWriter2, CultureInfo.InvariantCulture); csv2.WriteHeader<ExIRR>(); csv2.NextRecord(); foreach (var record in irrList) { csv2.WriteRecord(record); csv2.NextRecord(); } csv2.Flush(); stream2.Position = 0; //构建ZIP var compressedStream = new MemoryStream(); using (ZipFile zip = new ZipFile()) { zip.AddEntry("123.csv", stream); zip.AddEntry("456.csv", stream2); zip.Save(compressedStream); compressedStream.Position = 0; } return File(compressedStream, "application/zip"); } } }