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. 第三方库API接口

    第三方库API接口 InfluxDB提供了各种语言的Http API接口的封装.具体可以看这里: https://docs.influxdata.com/influxdb/v0.10/clients/ ...

  2. 【BZOJ 4031】: [HEOI2015]小Z的房间

    题目大意: 给一个n×m的网格,“.”表示可联通,求该网格可构成的生成树个数在1E9的剩余系中的结果.(n,m<=9) 题解: 忘了删注释WA了两遍…… 直接建图+MartrixTree定理即可 ...

  3. ZOJ_2314_Reactor Cooling_有上下界可行流模板

    ZOJ_2314_Reactor Cooling_有上下界可行流模板 The terrorist group leaded by a well known international terroris ...

  4. 深入css布局篇(2) — 定位与浮动

    深入css布局(2) - 定位与浮动      在css知识体系中,除了css选择器,样式属性等基础知识外,css布局相关的知识才是css比较核心和重要的点.今天我们来深入学习一下css布局相关的知识 ...

  5. java线程同步小结

    1.线程同步的目的是为了防止多个线程同时访问一个资源时对资源的破坏 2.线程同步方法是通过锁来实现,每个对象都有切仅有一个锁,这个锁与一个特定的对象关联,线程一旦获取了对象锁,其他访问该对象的线程就无 ...

  6. Java基础-常用的String方法

    先从String的new的方式 说起 这是面试题里面经常出现的 算是老套路之一 就是 比较下列两个的变化 两种实例化的区别 第一种String name1 = "好人";Strin ...

  7. Mendeley使用小技巧

    合并重复论文 在导入论文时,可能出现新导入的一篇论文是自己之前看过的,但是可能因为某些原因,如来源不是同一个网址,arxiv 和 ICCV,两篇相同内容的文献同时存在. Mendeley 提供一个方法 ...

  8. Vue之生命周期函数和钩子函数详解

    在学习vue几天后,感觉现在还停留在初级阶段,虽然知道怎么和后端做数据交互,但是对对vue的生命周期不甚了解.只知道简单的使用,而不知道为什么,这对后面的踩坑是相当不利的.因为我们有时候会在几个钩子函 ...

  9. 执行Python程序的两种方式

    目录 交互式(了解) 命令行式(了解) Python执行程序的三个阶段(掌握) 交互式(了解) 交互式环境下,敲完一条命令按下enter键马上能看到结果,调试程序方便.程序无法永久保存,关掉cmd窗口 ...

  10. udf提权原理详解

    0x00-前言 这个udf提权复现搞了三天,终于搞出来了.网上的教程对于初学者不太友好,以至于我一直迷迷糊糊的,走了不少弯路.下面就来总结一下我的理解. 想要知道udf提权是怎么回事,首先要先知道ud ...