npoi读写excel
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了npoi读写excel相关的知识,希望对你有一定的参考价值。
npoi读取excel方法:
首先下载:npoi.dll
添加引用:
//读写excel需要的组建
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.POIFS.FileSystem;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.OpenXml4Net;
IWorkbook workbook = null;//全局workbook
ISheet sheet;//sheet
FileStream fileStream = fileInfo.OpenRead();
switch (fileInfo.Extension)
{
//xls是03,用HSSFWorkbook打开,.xlsx是07或者10用XSSFWorkbook打开
case ".xls": workbook = new HSSFWorkbook(fileStream); break;
case ".xlsx": workbook = new XSSFWorkbook(fileStream); break;
default: break;
}
fileStream.Close();//关闭文件流
if (workbook != null)
{
sheet = workbook.GetSheetAt(0);//读取到指定的sheet
//遍历读取cell
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
for (int j = row.FirstCellNum; j < cellCount; j++)//读取cell值
{
value= row.GetCell(j).ToString()
}
}
}
npoi写入excel方法:
public void WriteToExcel(string path )
{
IWorkbook workbook = null;//全局workbook
ISheet sheet;//sheet
FileInfo fInfo = new FileInfo(path);
if(File.Exists(path))
{
FileStream fileStream = fInfo.OpenRead();
switch (fInfo.Extension)
{
//xls是03,用HSSFWorkbook打开,.xlsx是07或者10用XSSFWorkbook打开
case ".xls": workbook = new HSSFWorkbook(fileStream); break;
case ".xlsx": workbook = new XSSFWorkbook(fileStream); break;
default: break;
}
fileStream.Close();//关闭文件流
}
if (workbook != null)
{
sheet = workbook.GetSheetAt(0);
IRow headRow=sheet.GetRow(0);//取得表头,第一行一般为表头
int columCount=headRow.LastCellNum;//列数
for (int i = 0; i < TB.DataTable.Rows.Count; i++)
{
IRow row = sheet.CreateRow(i+1);
ICell cell = row.CreateCell(0);
cell.SetCellValue(setValue);//添加第一列
cell = row.CreateCell(1);
cell.SetCellValue(setValue);//添加第二列
}
//已下将写入的东西写入excel
FileStream file = new FileStream(path, FileMode.Open, FileAccess.Write);
workbook.Write(file);
file.Close();
}
}
以上是关于npoi读写excel的主要内容,如果未能解决你的问题,请参考以下文章