c# winform中使用NPOI,实现excel导入导出功能

1.在项目上右键——》管理Nuget包——》搜索NPOI——》安装

2.编写一个ExcelHelper类

class ExcelHelper
{
    /// <summary>
    /// 将DataTable数据保存至Excel文件
    /// </summary>
    /// <param name="dt"></param>
    /// <param name="txtPath"></param>
    /// <returns></returns>
    public static bool DataTableToExcel(DataTable dt, string txtPath)
    {
        bool result = false;
        IWorkbook workbook;
        FileStream? fs = null;
        IRow row;
        ISheet sheet;
        ICell cell;
        try
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                // 新建工作簿对象
                workbook = new HSSFWorkbook();
                sheet = workbook.CreateSheet("Sheet1");//创建一个名称为Sheet1的表
                int rowCount = dt.Rows.Count;//行数
                int columnCount = dt.Columns.Count;//列数

                //设置列头
                row = sheet.CreateRow(0);//excel第一行设为列头
                for (int c = 0; c < columnCount; c++)
                {
                    cell = row.CreateCell(c);
                    cell.SetCellValue(dt.Columns[c].ColumnName);
                }

                //设置每行每列的单元格,
                for (int i = 0; i < rowCount; i++)
                {
                    row = sheet.CreateRow(i + 1);
                    for (int j = 0; j < columnCount; j++)
                    {
                        cell = row.CreateCell(j);//excel第二行开始写入数据
                        cell.SetCellValue(dt.Rows[i][j].ToString());
                    }
                }
                using (fs = File.OpenWrite(txtPath))
                {
                    workbook.Write(fs);//向打开的这个xls文件中写入数据
                    result = true;
                }
            }
            MessageBox.Show("导出成功");
            return result;
        }
        catch (Exception)
        {
            fs?.Close();
            return false;
        }

    }


    /// <summary>
    /// 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值