zoukankan      html  css  js  c++  java
  • C#使用NPOI读写Excel的注意事项

    NPOI的基本使用参照:https://www.cnblogs.com/lixiaobin/p/NPOI.html

    既存文档读取修改方法

    *既存Excel文档修改保存注意使用FileMode.Create,不然文档将会被损害无法打开。

    *Excel文档不能有开启共享,不能有Object对象存在,否则重写的Excel文档会被损害无法打开。

                IWorkbook book = null;
                using (var file = File.Open(path, FileMode.OpenOrCreate, FileAccess.Read))
                {
                    book = WorkbookFactory.Create(file);
                    file.Close();
                }
    
                ISheet outputSheet = book?.GetSheet(sheetName) ?? book?.CreateSheet(sheetName);
    
                // 修改数据
                // 省略
    
                using (var file = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    book.Write(file);
                    file.Close();
                }

    单元格复制方法

    如果你想将一个Excel文档的值复制到另一个Excel文档,格式设置需要注意使用CloneStyleFrom方法。(最多只能创建4000个CellStyle)

                var sheet = book.CreateSheet("test");
                var row = sheet.CreateRow(1);
    
                var newCell=row.CreateCell(1);
                newCell.SetCellValue(oldCell.StringCellValue);
    
                var newCellStyle = book.CreateCellStyle();
                newCellStyle.CloneStyleFrom(oldCell.CellStyle);
    
                newCell.CellStyle = newCellStyle;

    颜色自定义

    如果NPOI自带的颜色不满足要求,可以自定义颜色。HSSFWorkbook的时候只能替换设置,XSSFWorkbook的场合是可以添加新的色调。

                var style = workbook.CreateCellStyle();
                style.BorderBottom = BorderStyle.Thin;
                style.BorderLeft = BorderStyle.Thin;
                style.BorderRight = BorderStyle.Thin;
                style.BorderTop = BorderStyle.Thin;
    
                var sysColor = Color.FromArgb(0, 32, 96);
                if (workbook is HSSFWorkbook)
                {
                    style.FillForegroundColor = IndexedColors.DarkBlue.Index;
                    ((HSSFWorkbook)workbook).GetCustomPalette().SetColorAtIndex(IndexedColors.DarkBlue.Index, sysColor.R, sysColor.G, sysColor.B);
                }
                else
                {
                    ((XSSFCellStyle)style).SetFillForegroundColor(new XSSFColor(sysColor));
                }
  • 相关阅读:
    python操作mysql封装成类
    es 数据 导出 到 MySQL
    Elasticsearch的数据导出和导入操作(elasticdump工具),以及删除指定type的数据(delete-by-query插件)
    解决VM虚拟机中的ubuntu不能全屏的问题
    pandas操作,感觉不错,复制过来的
    BTree和B+Tree详解
    ant安装配置
    jmeter默认生成测试报告
    学习网站
    selenium多窗口切换(windows)
  • 原文地址:https://www.cnblogs.com/lixiaobin/p/NPOIProblem.html
Copyright © 2011-2022 走看看