//我用的最新的2.2.1版本
//第一步:引用DLL,5个全导入,包括ICSHARP.ZIP,是个开源压缩工具包。XLSX是压缩格式,需要它来解压
//第二部:
using NPOI.SS.UserModel;
//够了
//第三部:用IWorkbook 接口,+WorkbookFactory类
//第四步:读取xlsx文件内容
StringBuilder sb = new StringBuilder();
using (FileStream fs = new FileStream(@"D:\temp\temp.xlsx", FileMode.Open, FileAccess.Read))
{
IWorkbook sswb = WorkbookFactory.Create(fs);
for(int i=0;i<sswb.NumberOfSheets;i++)
{
sb.Append("\r\n\r\n"+sswb.GetSheetName(i)+"\r\n");
ISheet sh = sswb.GetSheetAt(i);
for (int j = 0; j < sh.LastRowNum; j++)
{
IRow row = sh.GetRow(j);//读取当前行
if(row!=null)
{
sb.Append("\r\n----------------line"+j.ToString()+"--------------------------\r\n");
for (int k = 0; k < row.LastCellNum; k++)
{
ICell cell = row.GetCell(k);
if(cell!=null)
{
sb.Append(cell.ToString()+"|");
}
}
}
}
}
}
textBox1.Text = sb.ToString();
//第五步:写入xlsx文件
string file = @"D:\temp\test.xlsx";
IWorkbook wb = null;
using (FileStream fs = File.Open(file, FileMode.Open, FileAccess.Read,FileShare.Read))
{
wb = WorkbookFactory.Create(fs);
fs.Close();
}
ISheet sh = wb.GetSheetAt(0);
IRow row = sh.CreateRow(8);
ICell cell = row.CreateCell(0);
cell.SetCellValue(1);
using (FileStream fs = File.Open(file, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
wb.Write(fs);
fs.Close();
}
System.Diagnostics.Process.Start(Path.GetFullPath(file));
//对不起大家,我撒谎了,NPOI不支持XLSX文件输出。
//不会有错误提示,但生成的文件打开会“发现不可读取内容, xxxOOO..."