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

        }
    }
相关推荐
揭老师高效办公7 小时前
在Excel和WPS表格中为多个数字同时加上相同的数值
excel·wps表格
zzc92113 小时前
Wireshark导出数据包时间和长度
wireshark·excel·导出·csv·time·length·波形
Goona_15 小时前
PyQt多窗口应用开发:构建完整的可二次开发用户登录注册模板
python·小程序·excel·pyqt
用户03321266636717 小时前
Java 将 Excel 转换为 HTML:解锁数据在线展示的无限可能
java·excel
坐观垂钓者19 小时前
使用EasyExcel 导出复杂的合并单元格
java·excel
czhc11400756632 天前
LINUX 820 shell:shift,expect
linux·运维·excel
大霞上仙2 天前
实现自学习系统,输入excel文件,能学习后进行相应回答
python·学习·excel
CodeCraft Studio2 天前
在 Python 中操作 Excel 文件的高效方案 —— Aspose.Cells for Python
python·ui·excel·报表·aspose·aspose.cells
Techie峰2 天前
常见的 Bash 命令及简单脚本
chrome·bash·excel
小妖同学学AI2 天前
deepseek一键生成word和excel并一键下载
人工智能·word·excel·deepseek