NPOI 是 POI 项目的 .NET 版本。POI是一个开源的Java读写Excel、WORD等微软OLE2组件文档的项目。 使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写。 NPOI是构建在 POI 3.x版本之上的,它可以在没有安装 Office的情况下对 Word/Excel文档进行读写操作。 注意NPOI只能操作office2003的版本,07的版本不能操作; 下面是代码示例
static void Main(string[] args)
{
//创建一个工作薄,注意有些NPOI的程序集中的工作簿是IWorkBook,ISheet,IRow,ICell会有些许差别,大家使用的时候注意看它的属性
//向excel写数据
Workbook wk = new HSSFWorkbook();
//创建一个工作表
Sheet st = wk.CreateSheet("sww");
//创建一个表的行
Row row = st.CreateRow(0);
//创建行中的单元格
Cell cell0 = row.CreateCell(0);
//给单元格设置值
cell0.SetCellValue("sww");
Cell cell1 = row.CreateCell(1);
cell1.SetCellValue("100");
using (FileStream fs = new FileStream("1.xls", FileMode.Create, FileAccess.Write))
{
wk.Write(fs);
}
Console.WriteLine("OK");
Console.ReadKey();
//向excel读取数据并写入到txt文件中
using (FileStream fs = new FileStream("1.xls", FileMode.Open, FileAccess.Read))
{
Workbook wk1 = new HSSFWorkbook(fs);
Sheet st1 = wk1.GetSheet("sww");
for (int r = 0; r <= st1.LastRowNum; r++)
{
Row row1 = st1.GetRow(r);
List<string> list = new List<string>();
for (int c = 0; c < row1.LastCellNum; c++)
{
Cell cell = row1.GetCell(c);
list.Add(cell.ToString());
}
using(FileStream f = new FileStream("1.txt",FileMode.Create,FileAccess.Write))
{
using(StreamWriter writer = new StreamWriter(f,Encoding.GetEncoding("GB2312")))
{
writer.WriteLine(String.Join(",", list.ToArray()));
}
}
}
}
Console.WriteLine("OK");
Console.ReadKey();
}