使用 NPOI 对 xlsx 文档进行写入

1 引用 NPOI

如下图
在这里插入图片描述

在这里插入图片描述

2 代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace TestDemo
{
    /********************************
	* Author : Jeff Chen
	* Date : 2022/9/6 9:12:24
	* Description : Test for write to xslx
	*********************************/
    class XlsxTest
    {

        static void Main(String[] args)
        {
            Func();
        }

        static void Func()
        {
            // 创建 sheet
            var workbook = new XSSFWorkbook();
            string filePath = @"D:\Users\A0002486\Desktop\Test" + "\\myXlsx.xlsx";
            if (!File.Exists(filePath))
            {
                var vtable = workbook.CreateSheet("Hello");
                var vfs = File.OpenWrite(filePath);
                workbook.Write(vfs);   // 向打开的这个 xlsx 文件中写入名为 hello 的 sheet 表并保存。
                vfs.Close();
            }

            // 获取 xslx 对象
            FileStream fileStream = File.OpenRead(filePath);
            IWorkbook wk = new XSSFWorkbook(fileStream);
            fileStream.Close();

            // 设置单元格的值
            ISheet sheet = wk.GetSheetAt(0);
            IRow ir;
            int row = sheet.LastRowNum;
            int col = 0;
            if (sheet.LastRowNum == 0)
            {
                ir = sheet.CreateRow(row);
            }
            else
            {
                ir = sheet.GetRow(row);
            }
            // 第一行
            ir.CreateCell(col).SetCellValue(DateTime.Now.ToString("MM-dd"));
            col++;
            ir.CreateCell(col).SetCellValue("Test1");
            col++;
            ir.CreateCell(col).SetCellValue("Test2");
            col++;
            ir.CreateCell(col).SetCellValue("Test3");
            col++;
            ir.CreateCell(col).SetCellValue("Test4");

            // 第二行
            row++;
            if (row > sheet.LastRowNum)
                ir = sheet.CreateRow(row);
            else
                ir = sheet.GetRow(row);
            col = 0;
            ir.CreateCell(col).SetCellValue("value");
            col++;
            ir.CreateCell(col).SetCellValue("1");
            col++;
            ir.CreateCell(col).SetCellValue("2");
            col++;
            ir.CreateCell(col).SetCellValue("3");
            col++;
            ir.CreateCell(col).SetCellValue("4");

            // 写入 xlsx 文档
            fileStream = File.OpenWrite(filePath);
            wk.Write(fileStream);
            fileStream.Close();
        }
    }
}


运行结果如下:
在这里插入图片描述


版权声明:本文为m0_56651882原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。