C#利用NPOI操作Excel文件
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文件的更多相关文章
- 使用NPOI操作Excel文件及其日期处理
工作中经常遇到需要读取或导出Excel文件的情况,而NPOI是目前最宜用.效率最高的操作的Office(不只是Excel哟)文件的组件,使用方便,不详细说明了. Excel工作表约定:整个Excel表 ...
- .net利用NPOI生成excel文件
整理代码,这个是生成excel文件,用的是HSSF的方式,只能生成65535行,256列的数据,如果要看office07之后的生成,之前的随笔里提过.这个是一个完整的过程. 首先是已经查找好的数据,这 ...
- NPOI操作Excel文件
首先,通过NuGet添加NPOI. NPOI依赖SharpZipLib,通过NuGet添加SharpZipLib. 然后添加NPOI. 添加后项目的引用列表如下: 把DataTable转换成Excel ...
- C# WPF 利用NPOI读写Excel文件
https://blog.csdn.net/a312024054/article/details/70139172 [各种样式] https://www.cnblogs.com/xwgli/archi ...
- C#项目中操作Excel文件——使用NPOI库
转载自:http://blog.csdn.net/dcrmg/article/details/52356236# 感谢-牧野- 实际C#项目中经常会涉及到需要对本地Excel文件进行操作,特别是一些包 ...
- C#使用oledb操作excel文件的方法
本文实例讲述了C#使用oledb操作excel文件的方法.分享给大家供大家参考.具体分析如下: 不管什么编程语言都会提供操作Excel文件的方式,C#操作Excel主要有以下几种方式: 1.Excel ...
- NPOI操作Excel辅助类
/// <summary> /// NPOI操作excel辅助类 /// </summary> public static class NPOIHelper { #region ...
- Java生成和操作Excel文件(转载)
Java生成和操作Excel文件 JAVA EXCEL API:是一开放源码项目,通过它Java开发人员可以读取Excel文件的内容.创建新的Excel文件.更新已经存在的Excel文件.使用该A ...
- NPOI操作excel之写入数据到excel表
在上一篇<NPOI操作excel之读取excel数据>我们把excel数据写入了datatable中,本篇就讲如何把datatable数据写入excel中. using System; u ...
随机推荐
- c# 如何找到项目中图片的相对路径
c# 如何找到项目中图片的相对路径 string path = System.Environment.CurrentDirectory;//非Web程序if (System.Environment.C ...
- BZOJ_3626_[LNOI2014]LCA_离线+树剖
BZOJ_3626_[LNOI2014]LCA_离线+树剖 题意: 给出一个n个节点的有根树(编号为0到n-1,根节点为0).一个点的深度定义为这个节点到根的距离+1. 设dep[i]表示点i的深度, ...
- BZOJ_1861_[Zjoi2006]Book 书架_splay
BZOJ_1861_[Zjoi2006]Book 书架_splay 题意: 小T有一个很大的书柜.这个书柜的构造有些独特,即书柜里的书是从上至下堆放成一列.她用1到n的正整数给每本书都编了号. 小T在 ...
- NOIP2017 酱油送命记
Day0 一天,在机房,有点考前的紧张和慌张,打了一下午的模板,立了3个不该立的flag... Day1 拿到试题,万分紧张,T1是数论啊 害怕,一直以为D2T1才是数论,仔细观察却发现(flag1: ...
- Volley手写属于自己的万能网络访问框架
用户在调用层(Activity或Service中),发起一个网络请求,该请求肯定包含url,请求参数(requestParameter),以及我们需要给调用层提供一个请求成功或失败以后回调监听的接口d ...
- Centos打开、关闭、结束tomcat,及查看tomcat运行日志
cd到tomcat目录下之后 启动:一般是执行sh bin/startup.sh 停止:一般是执行sh bin/shutdown.sh查看:执行ps -ef |grep tomcat 输出如下 *** ...
- Java基础-方法重载和方法重写的区别
什么是java方法重载 (1) 方法重载是让类以统一的方式处理不同类型数据的一种手段.多个同名函数同时存在,具有不同的参数个数/类型. 重载Overloading是一个类中多态性的一种表现. (2) ...
- Vue.js-09:第九章 - 组件基础再探(data、props)
一.前言 在上一章的学习中,我们学习了 Vue 中组件的基础知识,知道了什么是组件,以及如何创建一个全局/局部组件.不知道你是否记得,在上一章中,我们提到组件是一个可以复用的 Vue 实例,它与 Vu ...
- asp.net core系列 59 Ocelot 构建基础项目示例
一.入门概述 从这篇开始探讨Ocelot,Ocelot是一个.NET API网关,仅适用于.NET Core,用于.NET面向微服务/服务的架构中.当客户端(web站点.ios. app 等)访问we ...
- Redis缓存穿透、缓存雪崩和缓存击穿理解
1.缓存穿透(不存在的商品访问数据造成压力) 缓存穿透,是指查询一个数据库一定不存在的数据.正常的使用缓存流程大致是,数据查询先进行缓存查询,如果key不存在或者key已经过期,再对数据库进行查询,并 ...