NPOI读取模板文件生成Excel

前不久实现了用NPOI组件替代Microsoft.Office.Interop.Excel 原生组件实现导出数据到Excel的需求,其中踩了几个坑,这里记录一下。

  • 不能使用wps创建模板文件
  • 不能使用一个文件流,对已存在Excel文件进行修改
  • NPOI中sheet、row、cell都是以0作为起始序号,Office原生组件是以1作为起始序号。

使用WPS创建的模板文件可以导出数据到Excel文件,但如果使用Office打开则可能出现 部分内容出错,询问是否修复的提示。用WPS打开时正常的。

使用一个文件流,对已存在Excel文件进行修改在保存时会出现异常,可以使用两个六对象,一个负责读取和修改,另外一个只负责写入,如下方代码所示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
public void ExportData(IList<IList<string>> items, string fullPathFileName, int startRowNumber, string title = "")
{
    Debug.Assert(items != null && items.Count > 0 && !string.IsNullOrWhiteSpace(fullPathFileName));
 
    IWorkbook workbook = null;
    try
    {
        using (FileStream fileStream = new FileStream(fullPathFileName, FileMode.Open, FileAccess.Read))
        {
            if (Path.GetExtension(fullPathFileName) == ".xlsx")
            {
                workbook = new XSSFWorkbook(fileStream);
            }
            else
            {
                workbook = new HSSFWorkbook(fileStream);
            }
            ISheet worksheet = workbook.GetSheetAt(0);
 
            worksheet.DefaultRowHeightInPoints = 17f;// 设置默认行高
 
            if (!string.IsNullOrWhiteSpace(title))
            {
                worksheet.Header.Center = title;
            }
 
            int rowIndex = 0;
            int columnIndex = 0;
            var firstCellStyle = worksheet.GetRow(rowIndex).GetCell(columnIndex).CellStyle;
 
            IFont font = workbook.CreateFont();
            font.FontHeightInPoints = 12;// 设置字体大小
            ICellStyle cellStyle = workbook.CreateCellStyle();
            cellStyle.SetFont(font);
            cellStyle.WrapText = true;// 自动换行
            cellStyle.BorderTop = firstCellStyle.BorderTop;
            cellStyle.BorderBottom = firstCellStyle.BorderBottom;
            cellStyle.BorderLeft = firstCellStyle.BorderLeft;
            cellStyle.BorderRight = firstCellStyle.BorderRight;
            cellStyle.VerticalAlignment = VerticalAlignment.Center;
 
            int rowsCount = items.Count;
            IRow currentRow;
            for (int dataIndex = 0; dataIndex < rowsCount; dataIndex++)
            {
                rowIndex = dataIndex + startRowNumber - 1;
                currentRow = worksheet.GetRow(rowIndex, true);
                currentRow.RowStyle = cellStyle;
                ICell currentCell;
                for (int j = 0; j < items[dataIndex].Count; j++)
                {
                    currentCell = currentRow.GetCell(j, true);
                    currentCell.SetCellType(CellType.String);// 设置单元格类型为字符串
                    currentCell.SetCellValue(items[dataIndex][j]);
                }
            }
        }
 
        // 保存
        using (FileStream outFileStream = new FileStream(fullPathFileName, FileMode.Create, FileAccess.Write))
        {
            workbook.Write(outFileStream);
        }
    }
    catch (OutOfMemoryException ex)
    {
        // LoggerFactory.CreateLog().LogError("Export data failed : {0}. Process.WorkingSet64: {1} MB.", ex.Message, Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024);
        throw;
    }
    catch (Exception ex)
    {
        // LoggerFactory.CreateLog().LogError("Export data failed:" + ex.Message);
        throw;
    }
    finally
    {
        workbook.Close();
    }
}

  

posted @   业荒于嬉  阅读(175)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
点击右上角即可分享
微信分享提示