因为我的个人网站 restran.net 已经启用,博客园的内容已经不再更新。请访问我的个人网站获取这篇文章的最新内容,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(0); IRow row = sheet.GetRow(0); //读取当前行数据
//LastRowNum 是当前表的总行数-1(注意)
int offset = 0;
for (int i = 0; i <= sheet.LastRowNum; i++)
{
row = sheet.GetRow(i); //读取当前行数据
if (row != null)
{
//LastCellNum 是当前行的总列数
for (int j = 0; 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 comes here
if (DateUtil.IsCellDateFormatted(cell))
{
value = cell.DateCellValue;
}
else
{
// Numeric type
value = cell.NumericCellValue;
}
break;
case CellType.Boolean:
// Boolean type
value = cell.BooleanCellValue;
break;
case CellType.Formula:
value = cell.CellFormula;
break;
default:
// String type
value = cell.StringCellValue;
break;
}
}
}
catch (Exception)
{
value = "";
} return value;
}

特别注意的是CellType中没有Date,而日期类型的数据类型是Numeric,其实日期的数据在Excel中也是以数字的形式存储。可以使用DateUtil.IsCellDateFormatted方法来判断是否是日期类型。

有了GetCellValue方法,写数据到Excel中的时候就要有SetCellValue方法,缺的类型可以自己补。

//根据数据类型设置不同类型的cell
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());
}
}

cell.SetCellValue()方法只有四种重载方法,参数分别是string, bool, DateTime, double, IRichTextString

设置公式使用cell.SetCellFormula(string formula)

写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;//文字垂直对齐方式 ICellStyle dateStyle = wb.CreateCellStyle();//样式
dateStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平对齐方式
dateStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直对齐方式
//设置数据显示格式
IDataFormat dataFormatCustom = wb.CreateDataFormat();
dateStyle.DataFormat = dataFormatCustom.GetFormat("yyyy-MM-dd HH:mm:ss"); //创建一个表单
ISheet sheet = wb.CreateSheet("Sheet0");
//设置列宽
int[] columnWidth = { 10, 10, 20, 10 };
for (int i = 0; i < columnWidth.Length; i++)
{
//设置列宽度,256*字符数,因为单位是1/256个字符
sheet.SetColumnWidth(i, 256 * columnWidth[i]);
} //测试数据
int rowCount = 3, columnCount = 4;
object[,] data = {
{"列0", "列1", "列2", "列3"},
{"", 400, 5.2, 6.01},
{"", true, "2014-07-02", DateTime.Now}
//日期可以直接传字符串,NPOI会自动识别
//如果是DateTime类型,则要设置CellStyle.DataFormat,否则会显示为数字
}; IRow row;
ICell cell; for (int i = 0; i < rowCount; i++)
{
row = sheet.CreateRow(i);//创建第i行
for (int j = 0; j < columnCount; j++)
{
cell = row.CreateCell(j);//创建第j列
cell.CellStyle = j % 2 == 0 ? style1 : style2;
//根据数据类型设置不同类型的cell
object obj = data[i, j];
SetCellValue(cell, data[i, j]);
//如果是日期,则设置日期显示的格式
if (obj.GetType() == typeof(DateTime))
{
cell.CellStyle = dateStyle;
}
//如果要根据内容自动调整列宽,需要先setCellValue再调用
//sheet.AutoSizeColumn(j);
}
} //合并单元格,如果要合并的单元格中都有数据,只会保留左上角的
//CellRangeAddress(0, 2, 0, 0),合并0-2行,0-0列的单元格
CellRangeAddress region = new CellRangeAddress(0, 2, 0, 0);
sheet.AddMergedRegion(region); try
{
FileStream fs = File.OpenWrite(filePath);
wb.Write(fs);//向打开的这个Excel文件中写入表单并保存。
fs.Close();
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
}

如果想要设置单元格为只读或可写,可以参考这里,方法如下:

ICellStyle unlocked = wb.CreateCellStyle();
unlocked.IsLocked = false;//设置该单元格为非锁定
cell.SetCellValue("未被锁定");
cell.CellStyle = unlocked;
...
//保护表单,password为解锁密码
//cell.CellStyle.IsLocked = true;的单元格将为只读
sheet.ProtectSheet("password");

cell.CellStyle.IsLocked 默认就是true,因此sheet.ProtectSheet("password")一定要执行,才能实现锁定单元格,对于不想锁定的单元格,就一定要设置cell的CellStyle中的IsLocked = false

C# 使用 NPOI 库读写 Excel 文件的更多相关文章

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

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

  2. C# 中 NPOI 库读写 Excel 文件的方法【摘】

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

  3. NPOI库读写Excel文件

    //首先Nuget安装NPOI库using System; using System.Data; using System.IO; using NPOI.HSSF.UserModel; using N ...

  4. MFC vs2012 Office2013 读写excel文件

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

  5. python 读写 Excel文件

    最近用python处理一个小项目,其中涉及到对excel的读写操作,通过查资料及实践做了一下总结,以便以后用. python读写excel文件要用到两个库:xlrd和xlwt,首先下载安装这两个库. ...

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

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

  7. Python使用openpyxl读写excel文件

    Python使用openpyxl读写excel文件 这是一个第三方库,可以处理xlsx格式的Excel文件.pip install openpyxl安装.如果使用Aanconda,应该自带了. 读取E ...

  8. Python使用读写excel文件

    Python使用openpyxl读写excel文件 这是一个第三方库,可以处理xlsx格式的Excel文件.pip install openpyxl安装.如果使用Aanconda,应该自带了. 读取E ...

  9. 【转发】Python使用openpyxl读写excel文件

    Python使用openpyxl读写excel文件 这是一个第三方库,可以处理xlsx格式的Excel文件.pip install openpyxl安装.如果使用Aanconda,应该自带了. 读取E ...

随机推荐

  1. 【GoLang】panic defer recover 深入理解

    唉,只能说C程序员可以接受go的错误设计,相比java来说这个设计真的很差劲! 我认为知乎上说的比较中肯的: 1. The key lesson, however, is that errors ar ...

  2. JQ引用

    <script type="text/javascript" src="http://files.cnblogs.com/914556495wxkj/jquery- ...

  3. 【leetcode】Word Break II

    Word Break II Given a string s and a dictionary of words dict, add spaces in s to construct a senten ...

  4. libreoffice安装

    centos7下libreoffice的安装 #下载安装包wget http://mirrors.ustc.edu.cn/tdf/libreoffice/stable/5.1.1/rpm/x86_64 ...

  5. STL vector按多字段值排序

    #include <iostream> #include <vector> #include <string> #include <algorithm> ...

  6. HDU 4865 Peter's Hobby(概率、dp、log)

    给出2个影响矩阵,一个是当天天气对湿度的影响,一个是前一天天气对当天天气的影响. 即在晴天(阴天.雨天)发生Dry(Dryish.Damp.Soggy)的概率,以及前一天晴天(阴天.雨天)而今天发生晴 ...

  7. Mathematics:Semi-prime H-numbers(POJ 3292)

      Semi-prime H-numbers 题目大意,令4n+1的数叫H数,H数素数x的定义是只能被x=1*h(h是H数),其他都叫合数,特别的,当一个数只能被两个H素数乘积得到时,叫H-semi数 ...

  8. iOS 本人必装插件

    本人觉得比较好用也实用的Xcode插件记录: 1. Alcatraz   插件通过它来管理 :    https://github.com/alcatraz/Alcatraz.git 2. Cocoa ...

  9. supersr--NSURLSessionConfiguration-下载进度

    ////  ViewController.m//  下载进度 // //  Created by Super on 14/7/4. //  Copyright (c) 2014年 iOS. All r ...

  10. 公共增删改查(MVC+三层架构)

    1.建立数据访问层:新建一个项目,选择类库,命名为XXXDAL,然后把新生成的类删除,重新建一个类BaseDal,代码如下: public class BaseDal<T> where T ...