NPOI作为开源免费的组件,功能强大,可用来读写Excel(兼容xls和xlsx两种版本)、Word、PPT文件。可是要让我们记住所有的操作,这便有点困难了,至此,总结一些在开发中常用的针对Excel的简单。NPOI官网地址

  本文地址:https://www.cnblogs.com/CKExp/p/9626022.html

一、NPOI的安装

  下载NPOI或是通过Nuget包加入进来,然后在代码中引用如下命名空间,然后开始读写Excel文件。

using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.SS.Util;

二、NPOI写入Excel文件

  在NPOI中,使用HSSFWorkbook类类来处理xls结尾的Excel文件(版本在2003及以前),XSSFWorkbook类来处理xlsx结尾的Excel文件(版本在2007及以后),都继承自接口IWorkbook,我们可以使用IWorkbook来统一处理两种不同格式的Excel文件。

  直接参考相关代码即可,对于合并单元格的跨行跨列操作,无需将被跨掉的行生成新行,合并单元格的信息是单独保存的。设置单元格样式时,请创建一个新的样式对象,不创建将使用默认的样式对象。

 /// <summary>
/// Datable导出到Excel
/// </summary>
/// <returns></returns>
public static void DataTableToExcel()
{
//一些已有数据信息
bool fileSaved = false;
SaveFileDialog saveDialog = new SaveFileDialog
{
DefaultExt = "xls",
Filter = "Excel文件|*.xls",
FileName = DateTime.Now.ToString("yyyyMMdd") + "-" + enterpriseTable.Rows[]["名称"].ToString() + "委托书"
};
saveDialog.ShowDialog();
string saveFileName = saveDialog.FileName;
if (saveFileName.IndexOf(":") < ) return; //被点了取消
if (saveFileName != "")
{
try
{
IWorkbook workbook;
string fileExt = System.IO.Path.GetExtension(saveFileName).ToLower();
if (fileExt == ".xlsx")
{
workbook = new XSSFWorkbook();
}
else if (fileExt == ".xls")
{
workbook = new HSSFWorkbook();
}
else
{
return;
} ISheet sheet = workbook.CreateSheet("Sheet1"); sheet.AddMergedRegion(new CellRangeAddress(, , , ));//合并单元格
IRow row = sheet.CreateRow();//创建首行
ICell cell = row.CreateCell();//行中创建第一列
cell.SetCellValue("标题");
ICellStyle style = workbook.CreateCellStyle();//设置样式,创建新的style实例,脱离统一样式
style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;//设置单元格的样式:水平对齐居中
style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; IFont font = workbook.CreateFont();//新建一个字体样式对象
font.Boldweight = short.MaxValue; //设置字体加粗样式
style.SetFont(font); //使用SetFont方法将字体样式添加到单元格样式中
cell.CellStyle = style; //将新的样式赋给单元格 sheet.AddMergedRegion(new CellRangeAddress(, , , ));
sheet.AddMergedRegion(new CellRangeAddress(, , , ));
row = sheet.CreateRow();
cell = row.CreateCell();
cell.SetCellValue("编号:");
cell = row.CreateCell();
cell.SetCellValue(planCode);
cell = row.CreateCell();
cell.SetCellValue("日期:");
cell = row.CreateCell();
cell.SetCellValue(taskPlantable.Rows[]["编制日期"].ToString()); sheet.AddMergedRegion(new CellRangeAddress(, , , ));
sheet.AddMergedRegion(new CellRangeAddress(, , , ));
row = sheet.CreateRow();
cell = row.CreateCell();
cell.SetCellValue("单位:");
cell = row.CreateCell();
cell.SetCellValue(enterpriseTable.Rows[]["名称"].ToString());
cell = row.CreateCell();
cell.SetCellValue("联系人:");
cell = row.CreateCell();
cell.SetCellValue(enterpriseTable.Rows[]["联系人"].ToString()); sheet.AddMergedRegion(new CellRangeAddress(, , , ));
sheet.AddMergedRegion(new CellRangeAddress(, , , ));
row = sheet.CreateRow();
cell = row.CreateCell();
cell.SetCellValue("传真:");
cell = row.CreateCell();
cell.SetCellValue(enterpriseTable.Rows[]["传真"].ToString());
cell = row.CreateCell();
cell.SetCellValue("联系电话:");
cell = row.CreateCell();
cell.SetCellValue(enterpriseTable.Rows[]["电话"].ToString()); sheet.AddMergedRegion(new CellRangeAddress(, , , ));
row = sheet.CreateRow();
cell = row.CreateCell();
cell.SetCellValue("详细地址:");
cell = row.CreateCell();
cell.SetCellValue(enterpriseTable.Rows[]["详细地址"].ToString()); int index = ;
//数据
for (int i = ; i < taskProjectTable.Rows.Count; i++)
{
index++;
sheet.AddMergedRegion(new CellRangeAddress(index, index, , ));
sheet.AddMergedRegion(new CellRangeAddress(index, index, , ));
row = sheet.CreateRow(index);
cell = row.CreateCell();
cell.SetCellValue("名称:");
cell = row.CreateCell();
cell.SetCellValue(taskProjectTable.Rows[i]["名称"].ToString());
cell = row.CreateCell();
cell.SetCellValue("类型:");
cell = row.CreateCell();
cell.SetCellValue(taskProjectTable.Rows[i]["项目类型"].ToString()); index++;
sheet.AddMergedRegion(new CellRangeAddress(index, index, , ));
sheet.AddMergedRegion(new CellRangeAddress(index, index, , ));
sheet.AddMergedRegion(new CellRangeAddress(index, index, , ));
row = sheet.CreateRow(index);
cell = row.CreateCell();
cell.SetCellValue("项目");
cell = row.CreateCell();
cell.SetCellValue("方法");
cell = row.CreateCell();
cell.SetCellValue("仪器"); //获取数据信息
DataTable taskDataTable = mysql.GetTableFromSQL(selstr.ToString());
selstr.Clear();
for (int j = ; j < taskDataTable.Rows.Count; j++)
{
index++;
sheet.AddMergedRegion(new CellRangeAddress(index, index, , ));
sheet.AddMergedRegion(new CellRangeAddress(index, index, , ));
sheet.AddMergedRegion(new CellRangeAddress(index, index, , ));
row = sheet.CreateRow(index);
cell = row.CreateCell();
cell.SetCellValue(taskDataTable.Rows[j]["名称"].ToString());
cell = row.CreateCell();
cell.SetCellValue(taskDataTable.Rows[j]["方法"].ToString());
cell = row.CreateCell();
cell.SetCellValue(taskDataTable.Rows[j]["仪器型号"].ToString());
}
} //转为字节数组
MemoryStream stream = new MemoryStream();
workbook.Write(stream);
var buf = stream.ToArray(); //保存为Excel文件
using (FileStream fs = new FileStream(saveDialog.FileName, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, , buf.Length);
fs.Flush();
}
fileSaved = true;
}
catch (Exception ex)
{
fileSaved = false;
MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
}
}
GC.Collect();//强行销毁 if (fileSaved && File.Exists(saveFileName))
{
MessageBox.Show("导出成功!", "通知");
Process.Start(saveFileName);
}
else
{
MessageBox.Show("导出失败!", "通知");
}
}

三、NPOI读取Excel文件

  打开指定Excel文件并读取文件中的内容,加入到DataTable中,或是加入到其它的数据载体中。

 /// <summary>
/// Excel导入成DataTble
/// </summary>
/// <param name="file">导入路径(包含文件名与扩展名)</param>
/// <returns></returns>
public static DataTable ExcelToTable(string file)
{
DataTable dt = new DataTable();
IWorkbook workbook;
string fileExt = Path.GetExtension(file).ToLower();
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
if (workbook == null) { return null; }
ISheet sheet = workbook.GetSheetAt(); //表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueType(header.GetCell(i));
if (obj == null || obj.ToString() == string.Empty)
{
dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
}
else
dt.Columns.Add(new DataColumn(obj.ToString()));
columns.Add(i);
}
//数据
for (int i = sheet.FirstRowNum + ; i <= sheet.LastRowNum; i++)
{
DataRow dr = dt.NewRow();
bool hasValue = false;
foreach (int j in columns)
{
dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
if (dr[j] != null && dr[j].ToString() != string.Empty)
{
hasValue = true;
}
}
if (hasValue)
{
dt.Rows.Add(dr);
}
}
}
return dt;
}

四、对单元格数据类型的操作

  获取目标单元格的数据类型及数据值。

 /// <summary>
/// 获取单元格类型
/// </summary>
/// <param name="cell">目标单元格</param>
/// <returns></returns>
private static object GetValueType(ICell cell)
{
if (cell == null)
return null;
switch (cell.CellType)
{
case CellType.Blank:
return null;
case CellType.Boolean:
return cell.BooleanCellValue;
case CellType.Numeric:
return cell.NumericCellValue;
case CellType.String:
return cell.StringCellValue;
case CellType.Error:
return cell.ErrorCellValue;
case CellType.Formula:
default:
return "=" + cell.CellFormula;
}
}

  将数据设置到目标单元格中,并设置为指定数据格式。

 /// <summary>
/// 设置单元格数据类型
/// </summary>
/// <param name="cell">目标单元格</param>
/// <param name="obj">数据值</param>
/// <returns></returns>
public static void SetCellValue(ICell cell, object obj)
{
if (obj.GetType() == typeof(int))
{
cell.SetCellValue((int)obj);
}
else if (obj.GetType() == typeof(double))
{
cell.SetCellValue((double)obj);
}
else if (obj.GetType() == typeof(IRichTextString))
{
cell.SetCellValue((IRichTextString)obj);
}
else if (obj.GetType() == typeof(string))
{
cell.SetCellValue(obj.ToString());
}
else if (obj.GetType() == typeof(DateTime))
{
cell.SetCellValue((DateTime)obj);
}
else if (obj.GetType() == typeof(bool))
{
cell.SetCellValue((bool)obj);
}
else
{
cell.SetCellValue(obj.ToString());
}
}

  本文地址:https://www.cnblogs.com/CKExp/p/9626022.html

2018-09-11,望技术有成后能回来看见自己的脚步

C#利用NPOI操作Excel文件的更多相关文章

  1. 使用NPOI操作Excel文件及其日期处理

    工作中经常遇到需要读取或导出Excel文件的情况,而NPOI是目前最宜用.效率最高的操作的Office(不只是Excel哟)文件的组件,使用方便,不详细说明了. Excel工作表约定:整个Excel表 ...

  2. .net利用NPOI生成excel文件

    整理代码,这个是生成excel文件,用的是HSSF的方式,只能生成65535行,256列的数据,如果要看office07之后的生成,之前的随笔里提过.这个是一个完整的过程. 首先是已经查找好的数据,这 ...

  3. NPOI操作Excel文件

    首先,通过NuGet添加NPOI. NPOI依赖SharpZipLib,通过NuGet添加SharpZipLib. 然后添加NPOI. 添加后项目的引用列表如下: 把DataTable转换成Excel ...

  4. C# WPF 利用NPOI读写Excel文件

    https://blog.csdn.net/a312024054/article/details/70139172 [各种样式] https://www.cnblogs.com/xwgli/archi ...

  5. C#项目中操作Excel文件——使用NPOI库

    转载自:http://blog.csdn.net/dcrmg/article/details/52356236# 感谢-牧野- 实际C#项目中经常会涉及到需要对本地Excel文件进行操作,特别是一些包 ...

  6. C#使用oledb操作excel文件的方法

    本文实例讲述了C#使用oledb操作excel文件的方法.分享给大家供大家参考.具体分析如下: 不管什么编程语言都会提供操作Excel文件的方式,C#操作Excel主要有以下几种方式: 1.Excel ...

  7. NPOI操作Excel辅助类

    /// <summary> /// NPOI操作excel辅助类 /// </summary> public static class NPOIHelper { #region ...

  8. Java生成和操作Excel文件(转载)

    Java生成和操作Excel文件   JAVA EXCEL API:是一开放源码项目,通过它Java开发人员可以读取Excel文件的内容.创建新的Excel文件.更新已经存在的Excel文件.使用该A ...

  9. NPOI操作excel之写入数据到excel表

    在上一篇<NPOI操作excel之读取excel数据>我们把excel数据写入了datatable中,本篇就讲如何把datatable数据写入excel中. using System; u ...

随机推荐

  1. Python软件目录结构规范

    设计项目目录结构和'代码编码风格'一样, 是为了达到以下两点: 可读性高 可维护性高 目录组织方式 Stackoverflow上有一些比较好的范式.

  2. dqname.go

    package nsqd func getBackendName(topicName, channelName string) string {     // backend names, for u ...

  3. Django运算表达式与Q对象/F对象

    Django运算表达式与Q对象/F对象 1 模型查询 概述: 1 查询集:表示从数据库中获取的对象的集合 2 查询集可以有多个过滤器,通过 逻辑运算符连接 3 过滤器就是一个函数,基于所给的参数限制查 ...

  4. Python + Appium 【已解决】driver(session)在多个class之间复用,执行完一个类的用例,再次执行下个类的用例时不需要初始化

    实现效果:打开App进行自动化测试,只需打开APP一次,按先后顺序执行n个py文件中的相应操作,实现自动化测试. 示例:如截图示例,一个App,根据此APP内不同的模块,写成了不同的py文件, 预期结 ...

  5. Lucene 源码分析之倒排索引(三)

    上文找到了 collect(-) 方法,其形参就是匹配的文档 Id,根据代码上下文,其中 doc 是由 iterator.nextDoc() 获得的,那 DefaultBulkScorer.itera ...

  6. Hadoop3.0 WordCount测试一直Accept 状态,Nodes of the cluster 页面node列表个数为0

    起因是我运行wordcount测试一直卡主,不能执行,一直处于 Accept 状态,等待被执行,刚开始是各种配置yarn参数,以及host配置,后来发现还是不行 hadoop 集群安装完成后,在500 ...

  7. FreeSql.Repository 通用仓储层功能

    前言 好多年前,DAL 作为数据库访问层,其实是非常流行的命名方式. 不知道从什么时候开始,仓储层成了新的时尚名词.目前了解到,许多人只要在项目中看见 DAL 就会觉得很 low,但是比较可笑的一点是 ...

  8. Python中使用面状矢量裁剪栅格影像,并依据Value值更改矢量属性

    本文整体思路:在Python中使用Geopandas库,依次读取shp文件的每一个面状要素,获取其空间边界信息并裁剪对应的栅格影像,计算所裁剪影像Value值的众数,将其设置为对应面状要素的NewTY ...

  9. python接口自动化(八)--发送post请求的接口(详解)

    简介 上篇介绍完发送get请求的接口,大家必然联想到发送post请求的接口也不会太难,被聪明的你又猜到了.答案是对的,虽然发送post请求的参考例子很简单,但是实际遇到的情况却是很复杂的,因为所有系统 ...

  10. vue客户端渲染首屏优化之道

    提取第三方库,缓存,减少打包体积 1. dll动态链接库, 使用DllPlugin DllReferencePlugin,将第三方库提取出来另外打包出来,然后动态引入html.可以提高打包速度和缓存第 ...