NPOI可以在没有安装Office的情况下对Word或Excel文档进行读写操作。
首先下载NPOI包(下面也有给出下载包),解压后里面有net20和net40文件夹,我们用net40,在我们的程序中添加里面的几个dll库文件;
1.从Excel文件中读取数据:
IWorkbook workbook = null; //新建IWorkbook对象
//string fileName = "E:\\Excel2003.xls";
string fileName = AppDomain.CurrentDomain.BaseDirectory + "\\Excel1.xlsx";
FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
{
workbook = new XSSFWorkbook(fileStream); //xlsx数据读入workbook
}
else if (fileName.IndexOf(".xls") > 0) // 2003版本
{
workbook = new HSSFWorkbook(fileStream); //xls数据读入workbook
}
ISheet sheet = workbook.GetSheetAt(0); //获取第一个工作表
IRow row;
//for (int i = 0; i < sheet.LastRowNum; i++) //对工作表每一行
//{
// row = sheet.GetRow(i); //row读入第i行数据
// if (row != null)
// {
// for (int j = 0; j < row.LastCellNum; j++) //对工作表每一列
// {
// string cellValue = row.GetCell(j).ToString(); //获取i行j列数据
// Console.WriteLine(cellValue);
// }
// }
//}
//for (int i = 0; i < sheet.LastRowNum; i++) //对工作表每一行
//{
// row = sheet.GetRow(i); //row读入第i行数据
// if (row != null)
// {
// for (int j = 0; j < row.LastCellNum; j++) //对工作表每一列
// {
// string cellValue = row.GetCell(j).ToString(); //获取i行j列数据
// //Console.WriteLine(cellValue);
// textBox1.Text = cellValue;
// }
// }
//}
row = sheet.GetRow(0);
textBox1.Text = row.GetCell(0).ToString();
textBox2.Text = row.GetCell(1).ToString();
textBox3.Text = sheet.GetRow(1).GetCell(1).ToString();
//Console.ReadLine();
fileStream.Close();
workbook.Close();
2.写入数据到Excel中:
HSSFWorkbook workbook = null;
string FileName = AppDomain.CurrentDomain.BaseDirectory + "\\Example.xls";
using (FileStream fs = File.Open(FileName, FileMode.Open, FileAccess.Read))
{
workbook = new HSSFWorkbook(fs);
ISheet sheet = null;
sheet = workbook.GetSheetAt(0);
IRow row = null;
row = sheet.CreateRow(1);
row.CreateCell(1).SetCellValue("hello");
t.ForceFormulaRecalculation = true;
using (FileStream filess = File.OpenWrite(FileName))
{
workbook.Write(filess);
}
NPOI组件链接:https://download.csdn.net/download/qq_43024228/11998616