标签:
NPOI 能够操作Excel,不需要注册 microsoft.ACE.oledb.12.0,只需要在project中添加NPOI的引用即可,十分方便。
第一部分:概念解释
1,Workbook 是Excel文件,在NPOI中,HSSFWorkbook操作的是xls文件,XSSFWorkbook操作的是xlsx文件。
2,ISheet 是Excel的一个sheet
3,IRow是sheet的一行
4,ICell是一个单元格
第二部分:示例代码
using System.IO;
using NPOI;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
public void CreateExcel() { XSSFWorkbook workbook = new XSSFWorkbook(); ISheet sheet = workbook.CreateSheet("sheet1"); int iColumnNo = 20; IRow rowHeader = sheet.CreateRow(0); for(int i=0;i<iColumnNo;i++) { ICell cell = rowHeader.CreateCell(i); cell.SetCellValue("ColumnName_" + i); } IRow row = sheet.CreateRow(1); for(int i=0;i<iColumnNo;i++) { ICell cell = row.CreateCell(i); cell.SetCellValue("cellvalue_"+i); } using(FileStream fs=new FileStream(@"D:\CreateExcel_Npoi.xlsx",FileMode.OpenOrCreate)) { workbook.Write(fs); } } public void ReadExcel() { StringBuilder sbContent = new StringBuilder(); string strExcelPath = @"D:\CreateExcel_Npoi.xlsx"; using(FileStream fs=new FileStream(strExcelPath,FileMode.Open)) { XSSFWorkbook workbook = new XSSFWorkbook(fs); for(int i=0;i<workbook.NumberOfSheets;i++) { sbContent.AppendLine(workbook.GetSheetName(i)); ISheet sheet = workbook.GetSheetAt(i); for(int j=0;j<=sheet.LastRowNum;j++) { IRow row=sheet.GetRow(j); for(int k=0;k<row.LastCellNum;k++) { ICell cell = row.GetCell(k); if(cell!=null) { sbContent.Append(cell.ToString() + " "); } } } sbContent.AppendLine(); } } using (StreamWriter sw = new StreamWriter(@"D:\ExcelNpoi.txt")) { sw.Write(sbContent.ToString()); sw.Flush(); } } public void UpdateExcel() { string strExcelPath = @"D:\CreateExcel_Npoi.xlsx"; XSSFWorkbook workbook; using (FileStream fs = new FileStream(strExcelPath, FileMode.Open)) { workbook = new XSSFWorkbook(fs); ISheet sheet = workbook.GetSheetAt(0); IRow row = sheet.GetRow(0); ICell cell = row.GetCell(0); string strCellValueNew = "UpdateExcel_SetCellNewValue"; cell.SetCellValue(strCellValueNew); } string strExcelPathNew= @"D:\CreateExcel_Npoi_New.xlsx"; using(FileStream fs=File.OpenWrite(strExcelPathNew)) { workbook.Write(fs); } }
更新Excel的时候,必须另存为一个Excel文件,在原有的Excel上进行更新,会失败,更新的数据丢失。
标签:
原文地址:http://www.cnblogs.com/ljhdo/p/4515312.html