当前位置: 移动技术网 > IT编程>开发语言>c# > NOPI 读与写

NOPI 读与写

2019年08月22日  | 移动技术网IT编程  | 我要评论

excel读取和写入的完整代码
using npoi.hssf.usermodel;
using npoi.ss.usermodel;
using npoi.xssf.usermodel;
using system;
using system.io;

namespace consoletest
{
class program
{
static void main(string[] args)
{
//readfromexcelfile(@"h:\班级文件(15软件)\15级软件工程班名单.xls");
writetoexcel(@"h:\班级文件(15软件)\15级软件工程班名单1.xls");
console.readkey();
}
public static void readfromexcelfile(string filepath)
{
iworkbook wk = null;
string extension = system.io.path.getextension(filepath);
try
{
using (filestream fs = file.openread(filepath))
{
if (extension.equals(".xls"))
{
//把xls文件中的数据写入wk中
wk = workbookfactory.create(fs);//new hssfworkbook(fs);
}
else
{
//把xlsx文件中的数据写入wk中
wk = workbookfactory.create(fs);//new xssfworkbook(fs);
}
}
//读取当前表数据
isheet sheet = wk.getsheetat(0);
irow row = sheet.getrow(0); //读取当前行数据
int offset = 0;
int lastrownum = sheet.lastrownum;//lastrownum 是当前表的总行数-1(注意)
for (int i = 0; i <= lastrownum; i++)
{
row = sheet.getrow(i); //读取当前行数据
if (row != null)
{
int lastcellnum= row.lastcellnum;
//lastcellnum 是当前行的总列数
for (int j = 0; j < lastcellnum; j++)
{
//读取该行的第j列数据
string value = row.getcell(j).tostring();
console.write(value.tostring() + " ");
}
console.writeline("\n");
}
}
}
catch (exception e)
{
//只在debug模式下才输出
console.writeline(e.message);
}
}
public static void writetoexcel(string filepath)
{
using (stream filestream = file.openwrite(filepath))
{
iworkbook wb = new xssfworkbook();//如果生成xls则是hssfworkbook
isheet sheet = wb.createsheet();
irow row = sheet.createrow(0);//0行号
row.createcell(0).setcellvalue("rupeng");
row.createcell(1).setcellvalue(3.14);
wb.write(filestream);
}

}
}
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网