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

        }
    }
相关推荐
缺点内向12 小时前
如何在C#中添加Excel文档属性?
开发语言·数据库·c#·.net·excel
shouchaobao12 小时前
仓库房进销存Excel模板合集:商品采购+出入库+库存统计一站式管理,适配仓库管理员/中小企业/个体商户
excel
chenhdowue13 小时前
如何使用 vxe-table 导出为带图片的单元格到 excel 格式文件
vue.js·excel·vxe-table·vxe-ui
码上成长13 小时前
从零实现:react&Ts--批量导入 & Excel 模版下载功能
javascript·react.js·excel
heartbeat..13 小时前
如何用 Excel / Java 去解决Excel下拉列表选项数量限制的问题(兼容.xsl和.xlsx)
java·开发语言·excel·poi
前端sweetGirl13 小时前
Excel 里 XLOOKUP 函数返回日期时找不到值显示 1/0,怎么让他不显示
excel
来鸟 鸣间1 天前
excel快速填充
excel
葡萄城技术团队1 天前
Excel 文件到底是怎么坏掉的?深入 OOXML 底层原理讲解修复策略
android·java·excel
程序边界1 天前
AI实战狂飙!Excel图表制作彻底解放双手:从数据清洗到智能预测全攻略
人工智能·excel
CodeCraft Studio1 天前
Excel处理控件Aspose.Cells教程:使用C#在Excel中创建漏斗图
ui·c#·excel·aspose·excel开发·excel漏斗图·漏斗图