使用第三类包:NPOI

介绍

Github地址:https://github.com/tonyqus/npoi,Java POI项目的.NET版。

通过它可以在没有安装Office软件的情况下,快速的读写Office文档。

特点:

  • 跨平台
  • 支持Office2003及以后所有版本
  • 支持Excel的大部分特性
  • 开源
  • 实例丰富
  • 维护者是中国人,所以交流应该问题不大

Nuget包下载:https://www.nuget.org/packages/NPOI/

实践一:读取Excel数据

注意:行列开始索引为0,没有数据的Cell为NULL。

        /// <summary>
/// 读取Excel所有单元格数据
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="sheetName">Sheet名</param>
/// <param name="startRow">读取开始行位置</param>
/// <param name="columns">读取列表</param>
/// <returns>单元格列表</returns>
public static async Task<IList<ICell>> ReadAllCellsAsync(string path, string sheetName, int startRow = , IList<int> columns = null)
{
var ret = new List<ICell>(); await Task.Factory.StartNew(() =>
{
using (var file = new FileStream(path, FileMode.Open, FileAccess.Read))
{
var book = WorkbookFactory.Create(file);
var sheet = book?.GetSheet(sheetName);
if (sheet != null)
{
for (int row = startRow - ; row <= sheet.LastRowNum; row++)
{
var rowValue = sheet.GetRow(row);
if (rowValue == null)
{
continue;
} if (columns == null || columns?.Count <= )
{
columns = Enumerable.Range(, rowValue.LastCellNum + ).ToList();
} foreach (int col in columns)
{
var cell = rowValue.GetCell(col - );
if (cell == null)
{
continue;
} ret.Add(cell);
}
}
}
book?.Close();
}
}); return ret;
}

取Cell值扩展函数

        public static string GetCellValue(this ICell cell)
{
if (cell == null)
{
return string.Empty;
} switch (cell.CellType)
{
case CellType.Formula:
case CellType.String:
return cell.StringCellValue;
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(cell))
{
return cell.DateCellValue.ToString();
}
else
{
return cell.NumericCellValue.ToString();
}
case CellType.Boolean:
return cell.BooleanCellValue.ToString();
default:
return string.Empty;
}
}

实践二:写Excel数据

1,创建Book。

        public static IWorkbook CreateBook(this string path)
{
IWorkbook book;
string extension = Path.GetExtension(path); // HSSF => Microsoft Excel(xls形式)(excel 97-2003)
// XSSF => Office Open XML Workbook形式(xlsx形式)(excel 2007+)
if (extension == ".xls")
{
book = new HSSFWorkbook();
}
else
{
book = new XSSFWorkbook();
} return book;
}

2,创建Sheet。

var sheet = book.CreateSheet(“test”);

3,创建单元格。(为了不区分HSSHyperLink与XSSFHyperLink直接使用了设置函数形式)

ICellStyle hlink_style = book.CreateCellStyle();
IFont hlink_font = book.CreateFont();
hlink_font.Underline = FontUnderlineType.Single;
hlink_font.Color = IndexedColors.Blue.Index;
hlink_style.SetFont(hlink_font); var row = sheet.GetRow(rowIndex) ?? sheet.CreateRow(rowIndex);
var cell = row.GetCell(columnIndex) ?? row.CreateCell(columnIndex); cell.SetCellValue("test"); // OR hyperlink
var linkcell = row.GetCell(columnIndex) ?? row.CreateCell(columnIndex);
linkcell.SetCellFormula($"hyperlink(\"{linkValue}\",\"{value}\")");
linkcell.CellStyle = hlink_style;

4,创建合并单元格。

sheet.AddMergedRegion(new CellRangeAddress(rowStart, rowEnd, columnStart, columnEnd));

5,创建单元格数据入力规则。

        public static void WriteValidation(this ISheet sheet, int rowStart, int rowEnd, int columnStart, int columnEnd, string[] values)
{
var addressList = new CellRangeAddressList(rowStart, rowEnd, columnStart, columnEnd);
var helper = sheet.GetDataValidationHelper();
var dataValidation = helper.CreateValidation(helper.CreateExplicitListConstraint(values), addressList); if (dataValidation is XSSFDataValidation)
{
dataValidation.SuppressDropDownArrow = true;
dataValidation.ShowErrorBox = true;
}
else
{
dataValidation.SuppressDropDownArrow = false;
}
dataValidation.EmptyCellAllowed = true;
dataValidation.ShowPromptBox = true;
sheet.AddValidationData(dataValidation);
}

6,创建过滤器。

sheet.SetAutoFilter(new CellRangeAddress(row + , row + , , col - ));

7,创建自动调整宽度。

 for (int i = ; i <= col; i++)
{
sheet.AutoSizeColumn(i, true);
}

8,单元格格式设置。

注意:如果所有单元格使用同一个ICellStyle实例,那CellStyle对象一样。

            var commonFont = book.CreateFont();
commonFont.Color = IndexedColors.Black.Index;
commonFont.FontHeightInPoints = ;
var Common= book.CreateCellStyle();
Common.SetFont(commonFont);
Common.BorderBottom = BorderStyle.Thin;
Common.BorderLeft = BorderStyle.Thin;
Common.BorderRight = BorderStyle.Thin;
Common.BorderTop = BorderStyle.Thin;
Common.WrapText = true;
Common.Alignment = HorizontalAlignment.Left;
Common.VerticalAlignment = VerticalAlignment.Center; var row = sheet.GetRow(rowIndex) ?? sheet.CreateRow(rowIndex);
var cell = row.GetCell(columnIndex) ?? row.CreateCell(columnIndex);
cell.CellStyle = Common;

9,单元格部分文字颜色设置。

           int rowIndex = ;
int columnIndex = ; var row = sheet.GetRow(rowIndex) ?? sheet.CreateRow(rowIndex);
var cell = row.GetCell(columnIndex) ?? row.CreateCell(columnIndex); IRichTextString richText;
if (sheet is HSSFSheet)
{
richText = new HSSFRichTextString("Microsoft OfficeTM");
}
else
{
richText = new XSSFRichTextString("Microsoft OfficeTM");
} //apply font to "Microsoft Office"
IFont redFont = workbook.CreateFont();
redFont.FontHeightInPoints = ;
redFont.Color = IndexedColors.Red.Index;
richText.ApplyFont(, , redFont); //apply font to "TM"
IFont blueFont = workbook.CreateFont();
blueFont.TypeOffset = FontSuperScript.Super;
blueFont.IsItalic = true;
blueFont.Color = IndexedColors.Blue.Index;
blueFont.FontHeightInPoints = ;
richText.ApplyFont(, , blueFont); var style = workbook.CreateCellStyle();
style.BorderBottom = BorderStyle.Thin;
style.BorderLeft = BorderStyle.Thin;
style.BorderRight = BorderStyle.Thin;
style.BorderTop = BorderStyle.Thin;
// 解决字体大小不一样问题
richText.ApplyFont(style.FontIndex);
cell.SetCellValue(richText);
cell.CellStyle = style;

实行结果:

这样通过NPOI基本的Excel操作就没问题了。

C#读写Excel实践笔记的更多相关文章

  1. 【原创】.NET读写Excel工具Spire.Xls使用(3)单元格控制

                  本博客所有文章分类的总目录:http://www.cnblogs.com/asxinyu/p/4288836.html .NET读写Excel工具Spire.Xls使用文章 ...

  2. C++读写EXCEL文件OLE,java读写excel文件POI 对比

    C++读写EXCEL文件方式比较 有些朋友问代码的问题,将OLE读写的代码分享在这个地方,大家请自己看.http://www.cnblogs.com/destim/p/5476915.html C++ ...

  3. Python编程从入门到实践笔记——文件

    Python编程从入门到实践笔记——文件 #coding=gbk #Python编程从入门到实践笔记——文件 #10.1从文件中读取数据 #1.读取整个文件 file_name = 'pi_digit ...

  4. 《python编程从入门到实践》读书实践笔记(一)

    本文是<python编程从入门到实践>读书实践笔记1~10章的内容,主要包含安装.基础类型.函数.类.文件读写及异常的内容. 1 起步 1.1 搭建环境 1.1.1 Python 版本选择 ...

  5. MFC vs2012 Office2013 读写excel文件

    近期在忙一个小项目(和同学一起搞的),在这里客户要求不但读写txt,而且可以读写excel文件,这里本以为很简单,结果...废话少说,过程如下: 笔者环境:win7 64+VS2012+Office2 ...

  6. C# 使用 NPOI 库读写 Excel 文件(转载)

    NPOI 是开源的 POI 项目的.NET版,可以用来读写Excel,Word,PPT文件.在处理Excel文件上,NPOI 可以同时兼 容xls 和 xlsx.官网提供了一份Examples,给出了 ...

  7. Python3.4如何读写Excel

    在python3.x(散仙使用的版本是python3.4)里,我们应该如何操作excel. 首先在python3.4里,我们可以使用新的python类库,来支持3.x之后的读写excel 针对 03版 ...

  8. 用Python读写Excel文件(转)

    原文:google.com/ncr 虽然天天跟数据打交道,也频繁地使用Excel进行一些简单的数据处理和展示,但长期以来总是小心地避免用Python直接读写Excel文件.通常我都是把数据保存为以TA ...

  9. 使用NPOI读写Excel、Word

    NPOI 是 POI 项目的 .NET 版本.POI是一个开源的Java读写Excel.WORD等微软OLE2组件文档的项目. 使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 ...

随机推荐

  1. foreach 使用 引用& $value . 使用 unset($value)

    1.知识点: 2. 例子 2.1 例子1 . $arr 引用循环, 赋值变量是 &$v ,第一个循环使用后 ,没有 使用unset($v) , $arr2 正常循环, 赋值变量是 $v ,  ...

  2. 斐讯 天天牛绑定教程 邀请码:8vozbf

    天天牛邀请码 8vozbf 可以领取4代牛 最近斐讯推出了天天牛养成计划. 不过官方没有任何的指示教程,所以个人分享一个教程给大家. 1. 先把把旧的钱包备份一下 ,切记!! 而且一定要记得自己设的密 ...

  3. MySQL中查询、删除重复记录的方法大全

    查找所有重复标题的记录: select title,count(*) as count from user_table group by title having count>1; SELECT ...

  4. cannot import name '_imaging' from 'PIL'

    学习廖雪峰官网的Python的教程,在常用的第三方模块的Pillow的学习过程中总是报错cannot import name '_imaging' from 'PIL' 解决办法: 1.下载并安装An ...

  5. golang 实现文件传输小demo

    获取文件信息需要用到os. Stat接口,发送文件前开启接收者(服务端),启动客户端先发送文件名给接收者,接收者收到文件名返回确认信息"ok",才读取本地文件 发送给接收者. 发送 ...

  6. C++中cin.getline与cin.get要注意的地方

    cin.getline与cin.get的区别是,cin.getline不会将结束符或者换行符残留在输入缓冲区中.

  7. WEB学习笔记9-添加必要的<meta>标签

    <meta>标签放置在HTML页面的head中,主要用于标示网站.其中主要包含网站的一些描述信息,如简介,作者等.这些信息有助于搜索引擎更准确地识别网页的内容,也有助于第三方工具抓取网站基 ...

  8. 从软件测试转型到C#上位机程序员

    一直在做软件测试的工作,天天与程序员不依不饶的争论细节的问题,没想到自己也有那么一天走上程序员的道路,由此开始,我的博客天天更新自己的学习状态,分享自己的心得. C#是微软公司发布的一种面向对象的.运 ...

  9. linux shell必知必会sed、awk

    sed是一种在线编辑器,它一次处理一行内容.处理时,把当前处理的行存储在临时缓冲区中,称为“模式空间”(pattern space),接着用sed命令处理缓冲区中的内容,处理完成后,把缓冲区的内容送往 ...

  10. jQuery-4.动画篇---动画基础隐藏和显示

    jQuery中隐藏元素的hide方法 让页面上的元素不可见,一般可以通过设置css的display为none属性.但是通过css直接修改是静态的布局,如果在代码执行的时候,一般是通过js控制元素的st ...