c# npoi 导出excel 简单应用

本文介绍了如何使用C#结合NPOI库将DataTable和List对象的数据导出为Excel文件。首先展示了如何将DataTable转换为Excel,然后讲解了如何处理List对象并创建对应的Excel工作表。代码中包含创建工作簿、设置表头和数据、保存到指定文件夹的步骤。

参考文章地址:https://blog.youkuaiyun.com/smartsmile2012/article/details/81559320

1. DataTable 导出excel       

public static int TableToExcel(DataTable dt, string fileName, Dictionary<string, string> cellheader)
        {
            string selectPath = string.Empty;
            int result = -1;
            try
            {
                FolderBrowserDialog dialog = new FolderBrowserDialog();
                dialog.Description = "请选择需存储的文件夹";

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    if (string.IsNullOrEmpty(dialog.SelectedPath))
                    {
                        FuncMessage.ShowErrorMsg("文件夹路径不能为空");
                    }
                    selectPath = dialog.SelectedPath;
                }

                string urlPath =Path.Combine( selectPath,fileName);
                IWorkbook workbook = new HSSFWorkbook();
                ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") :           

               workbook.CreateSheet(dt.TableName);

                //表头  
                IRow row = sheet.CreateRow(0);
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    ICell cell = row.CreateCell(i);
                    foreach (var item in cellheader)
                    {
                        if (dt.Columns[i].ColumnName == item.Key)
                        {
                            cell.SetCellValue(item.Value);
                            break;
                        }
                    }
                }

                //数据  
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    IRow row1 = sheet.CreateRow(i + 1);
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        ICell cell = row1.CreateCell(j);
                        cell.SetCellValue(dt.Rows[i][j].ToString());
                    }
                }

                using (FileStream fs = File.OpenWrite(urlPath))
                {
                    workbook.Write(fs);
                    result = 0;
                }
            }
            catch (Exception ex)
            {
                return -1;
            }
            return result;
        }

 

2.  List<> 导出excel

           List<KeyValuePair<string, string>> cellheader = new List<KeyValuePair<string, string>>();

            cellheader.Add(new KeyValuePair<string, string>("xxxxx", "xxxxxxx"));

           ......

         public static int TableToExcel<T>(List<T> dataList, string fileName, List<KeyValuePair<string, string>> cellheader)
        {
            string selectPath = string.Empty;
            int result = -1;

            try
            {
                FolderBrowserDialog dialog = new FolderBrowserDialog();
                dialog.Description = "请选择需存储的文件夹";

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    if (string.IsNullOrEmpty(dialog.SelectedPath))
                    {
                        FuncMessage.ShowErrorMsg("文件夹路径不能为空");
                    }
                    selectPath = dialog.SelectedPath;
                }

                string urlPath = Path.Combine(selectPath, fileName);

                IWorkbook workbook = new HSSFWorkbook();
                ISheet sheet = workbook.CreateSheet("Sheet1");
                IRow headerRow = sheet.CreateRow(0);
                for (int i = 0; i < cellheader.Count; i++)
                {
                    ICell cell = headerRow.CreateCell(i);
                    cell.SetCellValue(cellheader[i].Value);
                }

                Type t = typeof(T);
                int rowIndex = 1;
                foreach (T item in dataList)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex);
                    for (int n = 0; n < cellheader.Count; n++)
                    {
                        object pValue = t.GetProperty(cellheader[n].Key).GetValue(item, null);
                        dataRow.CreateCell(n).SetCellValue((pValue ?? "").ToString());
                    }
                    rowIndex++;
                }
                using (FileStream fs = File.OpenWrite(urlPath))
                {
                    workbook.Write(fs);
                    result = 0;
                }
            }
            catch (Exception ex)
            {
                return -1;
            }
            return result;
        }

### 使用 C#NPOI导出 Excel 文件并生成 CheckBox 控件 在 C# 中使用 NPOI 导出 Excel 并生成 CheckBox 控件是一个相对复杂的任务,因为 NPOI 主要用于操作单元格数据和样式,而 Excel 的 CheckBox 是 ActiveX 控件或表单控件,在纯后端环境中创建这些控件需要额外的技巧。 以下是详细的解决方案: #### 解决方案概述 NPOI 不支持直接生成 Excel 表单中的 CheckBox 控件。然而,可以通过以下方法间接实现此功能: 1. 创建一个带有预定义 CheckBox 的模板文件。 2. 在运行时加载该模板文件并通过 NPOI 修改其内容。 3. 将修改后的文件保存为最终的输出文件。 这种方法利用了 Excel 模板的功能,从而绕过了 NPOI 对复杂控件的支持不足问题[^3]。 #### 实现代码示例 下面提供了一个完整的代码示例,展示如何通过上述方法完成目标: ```csharp using System; using System.IO; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; class Program { static void Main(string[] args) { string templatePath = "TemplateWithCheckBox.xlsx"; // 预先准备好的带 CheckBox 的模板文件路径 string outputPath = "OutputWithCheckBox.xlsx"; // 输出文件路径 using (var fileStream = new FileStream(templatePath, FileMode.Open, FileAccess.Read)) { IWorkbook workbook = new XSSFWorkbook(fileStream); // 加载模板文件 ISheet sheet = workbook.GetSheetAt(0); // 向工作表中写入一些测试数据 int rowIndex = 1; // 起始行索引 var dataRows = new[] { new { Name = "Item A", Status = true }, new { Name = "Item B", Status = false } }; foreach (var rowData in dataRows) { IRow row = sheet.CreateRow(rowIndex++); row.CreateCell(0).SetCellValue(rowData.Name); row.CreateCell(1).SetCellValue((bool)rowData.Status ? "Checked" : "Unchecked"); } // 保存修改后的工作簿到输出文件 using (var outFileStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) { workbook.Write(outFileStream); } } Console.WriteLine($"Excel 文件已成功生成至: {outputPath}"); } } ``` #### 关键点说明 1. **模板文件的作用** 提前准备好一个包含 CheckBox 的 Excel 模板文件是非常重要的。这样可以避免在程序中动态生成 CheckBox 所带来的复杂性[^4]。 2. **数据填充逻辑** 上述代码展示了如何向模板文件中追加数据。虽然无法直接控制 CheckBox 的状态,但可以在相邻单元格中标记对应的布尔值(如 `true` 或 `false`),以便用户手动调整 CheckBox 状态。 3. **兼容性和限制** 此方法仅适用于 `.xlsx` 格式的文件,不支持旧版 `.xls` 格式。此外,由于 NPOI 不支持直接操作 Excel 表单控件,因此需要依赖模板文件来预先配置 CheckBox。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值