C# 使用 NPOI 库读写 Excel 文件(转载)
NPOI 是开源的 POI 项目的.NET版,可以用来读写Excel,Word,PPT文件。在处理Excel文件上,NPOI 可以同时兼 容xls 和 xlsx。官网提供了一份Examples,给出了很多应用场景的例子,打包好的二进制文件类库,也仅有几MB,使用非常方便。
读取Excel
NPOI使用HSSFWorkbook
类来处理xls,XSSFWorkbook
类来处理xlsx,它们都继承接口IWorkbook
,因此可以通过IWorkbook
来统一处理xls和xlsx格式的文件。
以下是简单的例子
public void ReadFromExcelFile(string filePath)
{
IWorkbook wk = null;
string extension = System.IO.Path.GetExtension(filePath);
try
{
FileStream fs = File.OpenRead(filePath);
if (extension.Equals(".xls"))
{
//把xls文件中的数据写入wk中
wk = new HSSFWorkbook(fs);
}
else
{
//把xlsx文件中的数据写入wk中
wk = new XSSFWorkbook(fs);
} fs.Close();
//读取当前表数据
ISheet sheet = wk.GetSheetAt(); IRow row = sheet.GetRow(); //读取当前行数据
//LastRowNum 是当前表的总行数-1(注意)
int offset = ;
for (int i = ; i <= sheet.LastRowNum; i++)
{
row = sheet.GetRow(i); //读取当前行数据
if (row != null)
{
//LastCellNum 是当前行的总列数
for (int j = ; j < row.LastCellNum; j++)
{
//读取该行的第j列数据
string value = row.GetCell(j).ToString();
Console.Write(value.ToString() + " ");
}
Console.WriteLine("\n");
}
}
} catch (Exception e)
{
//只在Debug模式下才输出
Console.WriteLine(e.Message);
}
}
Excel中的单元格是有不同数据格式的,例如数字,日期,字符串等,在读取的时候可以根据格式的不同设置对象的不同类型,方便后期的数据处理。
//获取cell的数据,并设置为对应的数据类型
public object GetCellValue(ICell cell)
{
object value = null;
try
{
if (cell.CellType != CellType.Blank)
{
switch (cell.CellType)
{
case CellType.Numeric:
// Date Type的数据CellType是Numeric
if (DateUtil.IsCellDateFormatted(cell))
{
value = cell.DateCellValue;
}
else
{
// Numeric type
value = cell.NumericCellValue;
}
break;
case CellType.Boolean:
// Boolean type
value = cell.BooleanCellValue;
break;
default:
// String type
value = cell.StringCellValue;
break;
}
}
}
catch (Exception)
{
value = "";
} return value;
}
特别注意的是CellType
中没有Date,而日期类型的数据类型是Numeric
,其实日期的数据在Excel中也是以数字的形式存储。可以使用DateUtil.IsCellDateFormatted
方法来判断是否是日期类型。
有了GetCellValue
方法,写数据到Excel中的时候就要有SetCellValue
方法,缺的类型可以自己补。
//根据数据类型设置不同类型的cell
public 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());
}
}
cell.SetCellValue()
方法只有四种重载方法,参数分别是string
, bool
, DateTime
,double
, IRichTextString
(公式用IRichTextString
)
写Excel
以下是简单的例子,更多信息可以参见官网提供的Examples。
public void WriteToExcel(string filePath)
{
//创建工作薄
IWorkbook wb;
string extension = System.IO.Path.GetExtension(filePath);
//根据指定的文件格式创建对应的类
if (extension.Equals(".xls"))
{
wb = new HSSFWorkbook();
}
else
{
wb = new XSSFWorkbook();
} ICellStyle style1 = wb.CreateCellStyle();//样式
style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平对齐方式
style1.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直对齐方式
//设置边框
style1.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
style1.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
style1.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
style1.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
style1.WrapText = true;//自动换行 ICellStyle style2 = wb.CreateCellStyle();//样式
IFont font1 = wb.CreateFont();//字体
font1.FontName = "楷体";
font1.Color = HSSFColor.Red.Index;//字体颜色
font1.Boldweight = (short)FontBoldWeight.Normal;//字体加粗样式
style2.SetFont(font1);//样式里的字体设置具体的字体样式
//设置背景色
style2.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;
style2.FillPattern = FillPattern.SolidForeground;
style2.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;
style2.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平对齐方式
style2.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直对齐方式 //创建一个表
ISheet tb = wb.CreateSheet("sheet0");
//设置列宽
int[] columnWidth = { , , , }; //测试数据
int rowCount = , columnCount = ;
object[,] data = {
{"列0", "列1", "列2", "列3"},
{"", , 5.2, 6.01},
{"", DateTime.Today, true, "2014-07-02"}
}; for (int i = ; i < columnWidth.Length; i++)
{
//设置列宽度,256*字符数,因为单位是1/256个字符
tb.SetColumnWidth(i, * columnWidth[i]);
} IRow row;
ICell cell;
for (int i = ; i < rowCount; i++)
{
row = tb.CreateRow(i);//创建第i行
for (int j = ; j < columnCount; j++)
{
cell = row.CreateCell(j);//创建第j列
cell.CellStyle = j % == ? style1 : style2;
//根据数据类型设置不同类型的cell
SetCellValue(cell, data[i, j]);
}
} //合并单元格,如果要合并的单元格中都有数据,只会保留左上角的
//CellRangeAddress(0, 2, 0, 0),合并0-2行,0-0列的单元格
CellRangeAddress region = new CellRangeAddress(, , , );
tb.AddMergedRegion(region); try
{
FileStream fs = File.OpenWrite(filePath);
wb.Write(fs); //向打开的这个xls文件中写入表并保存。
fs.Close();
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
}
转载自:http://www.cnblogs.com/restran/p/3889479.html
相关资料:
NPOI官网:http://npoi.codeplex.com/
NPOI大全:http://www.cnblogs.com/atao/category/209358.html
下载地址:NPOI 2.1 examples , NPOI 2.1.1 binary
C# 使用 NPOI 库读写 Excel 文件(转载)的更多相关文章
- C# 使用 NPOI 库读写 Excel 文件
NPOI 是开源的 POI 项目的.NET版,可以用来读写Excel,Word,PPT文件.在处理Excel文件上,NPOI 可以同时兼容 xls 和 xlsx.官网提供了一份 Examples,给出 ...
- C# 中 NPOI 库读写 Excel 文件的方法【摘】
原作:淡水网志 NPOI 是开源的 POI 项目的.NET版,可以用来读写Excel,Word,PPT文件.在处理Excel文件上,NPOI 可以同时兼容 xls 和 xlsx.官网提供了一份 Exa ...
- NPOI库读写Excel文件
//首先Nuget安装NPOI库using System; using System.Data; using System.IO; using NPOI.HSSF.UserModel; using N ...
- MFC vs2012 Office2013 读写excel文件
近期在忙一个小项目(和同学一起搞的),在这里客户要求不但读写txt,而且可以读写excel文件,这里本以为很简单,结果...废话少说,过程如下: 笔者环境:win7 64+VS2012+Office2 ...
- python 读写 Excel文件
最近用python处理一个小项目,其中涉及到对excel的读写操作,通过查资料及实践做了一下总结,以便以后用. python读写excel文件要用到两个库:xlrd和xlwt,首先下载安装这两个库. ...
- C++读写EXCEL文件OLE,java读写excel文件POI 对比
C++读写EXCEL文件方式比较 有些朋友问代码的问题,将OLE读写的代码分享在这个地方,大家请自己看.http://www.cnblogs.com/destim/p/5476915.html C++ ...
- Python使用openpyxl读写excel文件
Python使用openpyxl读写excel文件 这是一个第三方库,可以处理xlsx格式的Excel文件.pip install openpyxl安装.如果使用Aanconda,应该自带了. 读取E ...
- Python使用读写excel文件
Python使用openpyxl读写excel文件 这是一个第三方库,可以处理xlsx格式的Excel文件.pip install openpyxl安装.如果使用Aanconda,应该自带了. 读取E ...
- 【转发】Python使用openpyxl读写excel文件
Python使用openpyxl读写excel文件 这是一个第三方库,可以处理xlsx格式的Excel文件.pip install openpyxl安装.如果使用Aanconda,应该自带了. 读取E ...
随机推荐
- git Bash常用命令
1.Construct ssh key (If you want to commit to git server via THIS COMPUTER) git config --global user ...
- 个人学习记录1:二维数组保存到cookie后再读取
二维数组保存到cookie后再读取 var heartsArray = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0],[0,0, ...
- Java 对象 及 对象的应用
http://blog.chinaunix.net/xmlrpc.php?r=blog/article&uid=30149799&id=4942380原文地址
- 浅谈Android下的Bitmap之大Bitmap加载
引言 我们常常提到的“Android程序优化”,通常指的是性能和内存的优化,即:更快的响应速度,更低的内存占用.Android程序的性能和内存问题,大部分都和图片紧密相关,而图片的加载在很多情况下很用 ...
- 深入理解javascript原型和闭包(15)——闭包
前面提到的上下文环境和作用域的知识,除了了解这些知识之外,还是理解闭包的基础. 至于“闭包”这个词的概念的文字描述,确实不好解释,我看过很多遍,但是现在还是记不住. 但是你只需要知道应用的两种情况即可 ...
- NEERC2014 Eastern subregional
\ 先把furthur的超碉线段树粘过来 //#pragma comment(linker, "/STACK:102400000,102400000") #include<c ...
- alpha版、beta版、rc版的意思
很多软件在正式发布前都会发布一些预览版或者测试版,一般都叫“beta版”或者 “rc版”,特别是开源软件,甚至有“alpha版”,下面来解释一下各个版本的意思. alpha版:内部测试版.α是希腊字母 ...
- 初次使用并安装express
安装 Nodejs 去Nodejs官网根据自己的操作系统下载对应的安装包并安装.我们就有了NodeJS和npm环境.npm是Node的包管理工具,会在安装NodeJS时一并安装.可以用以下命令查看版本 ...
- UI第十三节——UIActionSheet
- (void)viewDidLoad { [super viewDidLoad]; UISwitch *swc = [[UISwitch alloc] initWithFrame ...
- 【Alpha版本】项目总结
我说的都队 031402304 陈燊 031402342 许玲玲 031402337 胡心颖 031402203 陈齐民 031402209 黄伟炜 031402233 郑扬涛 031402341 王 ...