首页 > 其他分享 >.Net Excel操作之NPOI(一)简介

.Net Excel操作之NPOI(一)简介

时间:2022-11-28 14:02:07浏览次数:65  
标签:cellStyle wb 单元格 Excel NPOI stylexls Net

一、NPOI简介

 NPOI是一个开源项目,可以读/写xls,doc,ppt文件,有着广泛的应用。

 使用NPOI能够帮助开发者在没有安装微软Office的情况下读写Office 97-2003的文件,支持的文件格式包括xls, doc, ppt等。NPOI是构建在POI 3.x版本之上的,它可以在没有安装Office的情况下对Word/Excel文档进行读写操作。

CodeFlex地址:http://npoi.codeplex.com/

Nuget地址:https://www.nuget.org/packages/NPOI

二、安装

Nuget命令

Install-Package NPOI

 或者使用Nuget包管理安装

 

 

 

 

 

 安装结果:

 

 

 

三、Excel操作示例

1.Excel函数问题:

      Excel 2003版本,最大行数是65536行。(xls)

HSSFWorkbook workbook = new HSSFWorkbook();

      Excel 2007版本以上,最大行数是1048576行。(xlsx)

XSSFWorkbook workbook = new XSSFWorkbook();

 2.创建Excel文件,并写入数据

//创建工作簿
HSSFWorkbook wk = new HSSFWorkbook();
//创建名称为mySheet的表
ISheet tb = wk.CreateSheet("mySheet");
//创建第一行,此行为第二行
IRow row = tb.CreateRow(1);
for (int i = 0; i < 20; i++)
{
    ICell cell = row.CreateCell(i); //创建单元格,写入数据
    cell.SetCellValue(i);
}

//保存到文件
//打开一个xls文件,如果没有自行创建
//如果存在则重新创建
using (FileStream fs = File.OpenWrite(LocalPathHelper.GetCurrentData() + "\\testone.xls"))
{
    wk.Write(fs);
    Console.WriteLine("导出数据成功!");
}

 

 3.创建Excel文件并设置单元格样式

/// <summary>
/// 创建xml 常用操作
/// </summary>
public static void TestTwo()
{
    IWorkbook wb = new HSSFWorkbook();
    //创建表  
    ISheet sh = wb.CreateSheet("zhiyuan");
    //设置单元的宽度  
    sh.SetColumnWidth(0, 15 * 256);
    sh.SetColumnWidth(1, 35 * 256);
    sh.SetColumnWidth(2, 15 * 256);
    sh.SetColumnWidth(3, 10 * 256);
    int i = 0;

    #region 练习合并单元格
    sh.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 3));
    //CellRangeAddress()该方法的参数次序是:开始行号,结束行号,开始列号,结束列号。
    IRow row0 = sh.CreateRow(0);
    row0.Height = 20 * 20;
    ICell icell1top0 = row0.CreateCell(0);
    icell1top0.CellStyle = Getcellstyle(wb, stylexls.头);
    icell1top0.SetCellValue("标题合并单元");
    #endregion

    i++;
    #region 设置表头
    IRow row1 = sh.CreateRow(1);
    row1.Height = 20 * 20;

    ICell icell1top = row1.CreateCell(0);
    icell1top.CellStyle = Getcellstyle(wb, stylexls.头);
    icell1top.SetCellValue("网站名");

    ICell icell2top = row1.CreateCell(1);
    icell2top.CellStyle = Getcellstyle(wb, stylexls.头);
    icell2top.SetCellValue("网址");

    ICell icell3top = row1.CreateCell(2);
    icell3top.CellStyle = Getcellstyle(wb, stylexls.头);
    icell3top.SetCellValue("百度快照");

    ICell icell4top = row1.CreateCell(3);
    icell4top.CellStyle = Getcellstyle(wb, stylexls.头);
    icell4top.SetCellValue("百度收录");
    #endregion

    using (FileStream stm = File.OpenWrite(LocalPathHelper.GetCurrentData() + "\\site.xls"))
    {
        wb.Write(stm);
        Console.WriteLine("导出数据成功");
    }
}
#region 定义单元格常用到样式的枚举
public enum stylexls
{
    头,
    url,
    时间,
    数字,
    钱,
    百分比,
    中文大写,
    科学计数法,
    默认
}
#endregion
#region 定义单元格常用到样式
static ICellStyle Getcellstyle(IWorkbook wb, stylexls str)
{
    ICellStyle cellStyle = wb.CreateCellStyle();

    //定义几种字体  
    //也可以一种字体,写一些公共属性,然后在下面需要时加特殊的  
    IFont font12 = wb.CreateFont();
    font12.FontHeightInPoints = 12;
    font12.FontName = "微软雅黑";


    IFont font = wb.CreateFont();
    font.FontName = "微软雅黑";
    //font.Underline = 1;下划线  


    IFont fontcolorblue = wb.CreateFont();
    fontcolorblue.Color = HSSFColor.OliveGreen.Blue.Index;
    fontcolorblue.IsItalic = true;//下划线  
    fontcolorblue.FontName = "微软雅黑";


    //边框  
    cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Dotted;
    cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Hair;
    cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Hair;
    cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Dotted;
    //边框颜色  
    cellStyle.BottomBorderColor = HSSFColor.OliveGreen.Blue.Index;
    cellStyle.TopBorderColor = HSSFColor.OliveGreen.Blue.Index;

    //背景图形,我没有用到过。感觉很丑  
    cellStyle.FillForegroundColor = HSSFColor.White.Index;
    // cellStyle.FillPattern = FillPatternType.NO_FILL;  
    cellStyle.FillBackgroundColor = HSSFColor.Blue.Index;

    //水平对齐  
    cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;

    //垂直对齐  
    cellStyle.VerticalAlignment = VerticalAlignment.Center;

    //自动换行  
    cellStyle.WrapText = true;

    //缩进;当设置为1时,前面留的空白太大了。希旺官网改进。或者是我设置的不对  
    cellStyle.Indention = 0;

    //上面基本都是设共公的设置  
    //下面列出了常用的字段类型  
    switch (str)
    {
        case stylexls.头:
            // cellStyle.FillPattern = FillPatternType.LEAST_DOTS;  
            cellStyle.SetFont(font12);
            break;
        case stylexls.时间:
            IDataFormat datastyle = wb.CreateDataFormat();

            cellStyle.DataFormat = datastyle.GetFormat("yyyy/mm/dd");
            cellStyle.SetFont(font);
            break;
        case stylexls.数字:
            cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00");
            cellStyle.SetFont(font);
            break;
        case stylexls.钱:
            IDataFormat format = wb.CreateDataFormat();
            cellStyle.DataFormat = format.GetFormat("¥#,##0");
            cellStyle.SetFont(font);
            break;
        case stylexls.url:
            fontcolorblue.Underline = FontUnderlineType.Single;
            cellStyle.SetFont(fontcolorblue);
            break;
        case stylexls.百分比:
            cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00%");
            cellStyle.SetFont(font);
            break;
        case stylexls.中文大写:
            IDataFormat format1 = wb.CreateDataFormat();
            cellStyle.DataFormat = format1.GetFormat("[DbNum2][$-804]0");
            cellStyle.SetFont(font);
            break;
        case stylexls.科学计数法:
            cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00E+00");
            cellStyle.SetFont(font);
            break;
        case stylexls.默认:
            cellStyle.SetFont(font);
            break;
    }
    return cellStyle;


}
#endregion

 

 4.读取Excel文件数据

StringBuilder sbr = new StringBuilder();
        using (FileStream fs = File.OpenRead(LocalPathHelper.GetCurrentData() + "\\site.xls"))
        {
            HSSFWorkbook wk = new HSSFWorkbook(fs);//读取xls文件中的数据写入wk中
            for (int i = 0; i < wk.NumberOfSheets; i++) //NumberOfSheets是总共的表数 
            {
                ISheet sheet = wk.GetSheetAt(i); //读取当前表数据
                for (int j = 0; j <= sheet.LastRowNum; j++) //LastRowNum 最后一行的索引,从0开始
                {
                    IRow row = sheet.GetRow(j);//获取当前行数据
                    if (row != null)
                    {
                        sbr.Append("\r\n--------------------------------\r\n");
                        for (int k = 0; k <= row.LastCellNum; k++) //LastCellNum 最后一列的索引,从0开始
                        {
                            ICell cell = row.GetCell(k); //获取当前单元格
                            if (cell != null)
                            {
                                sbr.Append(cell.ToString() + "\t");
                            }
                        }
                    }
                }
            }

        }

        //将读取的Xml文件数据写入到txt中
        using (StreamWriter sw = new StreamWriter(new FileStream(LocalPathHelper.GetCurrentData() + "\\test1.txt", FileMode.Append)))
        {
            sw.Write(sbr.ToString());
            sw.Flush();
            Console.WriteLine("读取数据成功!");
        }

 

 

 

MissingCellPolicy 枚举

如果你在一行中迭代列,一些空白的单元格甚至可能不存在,这可能导致毫无疑问的代码抛出一个NullPointerException.A MissingCellPolicy,当传递给它时getCell,引导并简化代码,告诉Apache POI如何处理这些类型的单元格.

  • CREATE_NULL_AS_BLANK - 如果Cell返回的不存在,则null创建Cell一个单元格类型为"blank" 的new ,而不是返回.这有助于避免NullPointerException方便.
  • RETURN_BLANK_AS_NULL - 即使单元格存在但单元格类型为"空白",也返回null.这可以让您忽略容易存在的空白单元格.
  • RETURN_NULL_AND_BLANK - 不要修改现有结构; 返回null不存在的单元格,如果存在,则返回空白Cell但其单元格类型为空.这是getCell不需要MissingCellPolicy重载行为.
ICell cell1 = row.GetCell(0,MissingCellPolicy.RETURN_BLANK_AS_NULL);

 

标签:cellStyle,wb,单元格,Excel,NPOI,stylexls,Net
From: https://www.cnblogs.com/funiyi816/p/16932002.html

相关文章

  • .Net Excel操作之NPOI(二)常用操作封装
    一、Excel数据导出常用操作1.指定表头和描述2.指定数据库中读出的数据集合二、ExcelExport封装///<summary>///Excel常用的表格导出逻辑封装///单表写入///</s......
  • pytest + excel参数驱动
    背景最近紧急支持一个接口测试,打算把接口的参数都放到execl中维护,且一个接口需要请求两次。思路1.execl中构造参数接口需要请求两次或者多次,比较两次后台返回的结果,那......
  • Centos 7.9 部署Kubernetes集群 (基于containerd 运行时)
    前言当Kubernetes社区宣布1.20版本之后会逐步弃用dockershim,当时也有很多自媒体在宣传Kubernetes弃用Docker。其实,我觉得这是一种误导,也许仅仅是为了蹭热度。dockersh......
  • 此功能需要连接到internet。是否允许office连接到internet
     问题在OneNote中进行一些操作的时候提示:此功能需要连接到internet。是否允许office连接到internet  解决方法1.快捷键Win+R,打开"运行"对话框 2.输......
  • .NET 6 实现滑动验证码(二)、基本数据
    上一节,介绍了滑动验证码的基本情况,也创建了一个.NET6的工程。本节内容是创建一些基础类。目录CaptchaData.csCaptchaValidateData.csImageCaptchaInfo.csResource.csSl......
  • .Net 6 配置日志
    前言  .Net6与之前的配置有点不一样了记录下日志配置方式。当前日志以Serilog为例,.Net6的日志由内置的Logger获取,然后可以交给Serilog|NLog等框架处理,框架通过他......
  • [Office] 如何阻止 Word 和 Excel 打开新文档的同时弹出已最小化的文档
    Word按Win+R,输入regedit打开注册表编辑器,转到HKEY_CLASSES_ROOT\Word.Document.12\shell\Open\command,右侧有个默认项,双击修改值为"C:\ProgramFiles(x86)\Micros......
  • java将List<Map<String,Object>>导出Excel
    遇到了个需要导出Excel的需求,经过百度查到方法在此记录一下:publicstaticvoidcreateExcel(List<Map<String,Object>>mapList,Stringfilename,Stringtitle,Http......
  • SQL serve 安装报错,缺少.net3.5组件
    今天安装sqlserver2014,遇到服务器没有安装.net3.5,的报错,上网搜索一番,找到一篇博文(非常详细,拷贝进来以备后用)操作之后略有区别,为表尊重原文地址https://www.cnblogs.co......
  • Use Kubekey to quickly deploy Kubernetes
    IntroductionStartwritingdeploymentprofilesStartthedeploymentDeploymentcomplete,checkpodstatusIntroductionKubekeyisanopensourceKubernetes......