使用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));
                }
            }

        }
    }
相关推荐
鲁Q同志8 分钟前
若依导出模板时设置动态excel下拉框(表连接的)
java·excel
弓.长.28 分钟前
从Excel到知识图谱再到数据分析:数据驱动智能体构建指南
数据分析·excel·知识图谱
写写闲篇儿4 小时前
将多个Excel合并到一个Excel中的方法
excel
葡萄城技术团队5 小时前
这几个 Excel 提升办公效率方法,你知道吗?
excel
流浪猪头拯救地球5 小时前
WPS 和 office (word/excel/ppt) 找到模板所在位置以及更改模板的方式(公文写作格式要求、字体安装、模板下载)
word·excel·wps
KellenKellenHao7 小时前
Rsync实操
excel
2501_920552568 小时前
Mac电脑 Office 2024 LTSC 长期支持版(Excel、Word、PPT)
macos·word·powerpoint·excel·mac
爱上妖精的尾巴1 天前
3-18 WPS JS宏 颜色设置实例应用(按条件设置单元格颜色)学习笔记
javascript·笔记·学习·excel·wps·js宏·jsa
最美不过下雨天啊1 天前
tp框架导出excel的时候报错:unexcepted identifier “Closure“,excepting variable
php·excel·thinkphp6