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

        }
    }
相关推荐
LAM LAB4 天前
【VBA】Excel指定单元格范围内字体设置样式,处理导出课表单元格
excel·vba
在这habit之下4 天前
Keepalived学习总结
excel
Youngchatgpt4 天前
如何在 Excel 中使用 ChatGPT:自动化任务和编写公式
人工智能·chatgpt·自动化·excel
开开心心就好4 天前
安卓开源应用,超时提醒紧急人护独居安全
windows·决策树·计算机视觉·pdf·计算机外设·excel·动态规划
D_C_tyu4 天前
Vue3 + Element Plus | el-table 多级表头表格导出 Excel(含合并单元格、单元格居中)第二版
vue.js·elementui·excel
骆驼爱记录4 天前
WPS页码设置:第X页共Y-1页
自动化·word·excel·wps·新人首发
Cxiaomu5 天前
Python 文件解析: Excel / Word / PDF 的解析、处理、预览与下载
python·word·excel
2501_930707785 天前
如何使用C#代码从 PDF 中提取表格并另存为Excel文件
pdf·excel
pacong5 天前
B生所学EXCEL
人工智能·excel