使用NPOI库导出多个Excel并压缩zip包

使用NPOI库导出Excel文件可以按照以下步骤进行:

  1. 添加NPOI库的引用:在项目中添加对NPOI库的引用。

  2. 创建一个新的Excel文件对象:使用NPOI中的HSSFWorkbook(对应.xls格式)或XSSFWorkbook(对应.xlsx格式)来创建一个新的Excel文件对象。

csharp 复制代码
var workbook = new HSSFWorkbook(); // 或者使用 XSSFWorkbook()
  1. 创建一个工作表对象:使用workbook.CreateSheet()方法创建一个新的工作表对象。
csharp 复制代码
var sheet = workbook.CreateSheet("Sheet1");
  1. 创建行和单元格:使用sheet.CreateRow()方法创建新的行对象,然后使用row.CreateCell()方法在行中创建单元格。
csharp 复制代码
var row = sheet.CreateRow(0);
var cell = row.CreateCell(0);
  1. 设置单元格的值:使用cell.SetCellValue()方法设置单元格的值。
csharp 复制代码
cell.SetCellValue("Hello World!");
  1. 保存Excel文件:使用FileStream将Excel文件保存到指定的路径。
csharp 复制代码
using (var fs = new FileStream("path/to/file.xls", FileMode.Create, FileAccess.Write))
{
    workbook.Write(fs);
}

完整的示例代码如下:

csharp 复制代码
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var workbook = new HSSFWorkbook();
        var sheet = workbook.CreateSheet("Sheet1");
        var row = sheet.CreateRow(0);
        var cell = row.CreateCell(0);
        cell.SetCellValue("Hello World!");

        using (var fs = new FileStream("path/to/file.xls", FileMode.Create, FileAccess.Write))
        {
            workbook.Write(fs);
        }
    }
}

注意:在使用NPOI库之前,需要将该库添加到项目中,可以通过NuGet包管理器添加NPOI库的引用。

接口示例

cs 复制代码
  /// <summary>
        /// 导出
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public FileStreamResult ExportExcel(List<IdInDto> ids)
        {
           
            string zipPath = @$"{ExcelExporter.GetImportDir()}\{GUIDHelper.NewGuid}.zip";
            foreach (var item in dic)
            {
                string filePath = @$"{ExcelExporter.GetImportDir()}\{item.Key}.xlsx";
               //生成excel逻辑
                ExcelExporter.AddFileToZip(zipPath, filePath);
            }

            FileStream fileStream = new FileStream(zipPath, FileMode.Open, FileAccess.Read);
            return new FileStreamResult(fileStream, "application/octet-stream") { FileDownloadName = "导出.zip" };

        }
cs 复制代码
  public class ExcelExporter
    {
        /// <summary>
        /// 创建目录
        /// </summary>
        /// <returns></returns>
        public static string GetImportDir()
        {
            string fileFolder = Path.Combine(AppContext.BaseDirectory, $"Export");
            fileFolder += "\\" + DateTime.Now.Date.ToString("yyyy-MM-dd");
            FileHelper.CreateIfNotExists(fileFolder);

            return fileFolder;
        }

        /// <summary>
        /// 添加文件到zip
        /// </summary>
        /// <param name="zipPath"></param>
        /// <param name="fileToAdd"></param>
        /// <exception cref="FileNotFoundException"></exception>
        public static void AddFileToZip(string zipPath, string fileToAdd)
        {
            // 确保要添加的文件存在
            if (!File.Exists(fileToAdd))
            {
                throw new FileNotFoundException("文件未找到。");
            }

            // 确保ZIP文件存在
            if (!File.Exists(zipPath))
            {
                using (ZipArchive zipArchive = ZipFile.Open(zipPath, ZipArchiveMode.Create))
                {
                    // 添加文件到ZIP文件中
                    zipArchive.CreateEntryFromFile(fileToAdd, Path.GetFileName(fileToAdd));
                }
            }
            else
            {
                using (ZipArchive zipArchive = ZipFile.Open(zipPath, ZipArchiveMode.Update))
                {
                    // 添加文件到ZIP文件中
                    zipArchive.CreateEntryFromFile(fileToAdd, Path.GetFileName(fileToAdd));
                }
            }

        }
    }
相关推荐
Allstar_4320 小时前
制造业研发管理数字化:从 Excel 到专业 APQP 系统的架构选型思考
架构·excel
驾驭人生20 小时前
NET NPOI 实战:生成带下拉、数据校验、必填标红的 Excel 导入模板
excel
泡海椒20 小时前
把 TRANSFORM 做成可扩展能力:JQuick-Excel 的函数与 SPI 调用链
驱动开发·excel
2601_962780911 天前
2027采购岗准备:大数据管理与应用专业如何把Excel、SQL变成业务能力
excel
开开心心_Every1 天前
文件查重软件批量删除重复文件释放空间
java·开发语言·c#·计算机外设·ocr·excel·perl
泡海椒1 天前
Spring 项目中如何组织 JQuick-Excel 的 XML 与 Bean
xml·spring·excel
死磕音视频1 天前
Microsoft Copilot 办公入门:在 Word、Excel、PowerPoint 里用 AI 完成日常文档工作
word·excel·copilot·办公效率
Access开发易登软件1 天前
我全新开发了一套 Access 通用 Excel 导入工具,现在开源了
数据库·microsoft·excel·mfc·vba·access·access开发
泡海椒1 天前
图表与主题如何设计扩展:基于 JQuick-Excel 现有工厂的工程化做法
excel
积流成海1 天前
CSV与JSON转换:RFC 4180 转义规则与 Excel 中文乱码
json·excel·盘子工具站