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


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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值