NPOI简单读写Excel
在这里只是简单记录一下NPOI的一个最基本的简单用法,以作备忘。
写入Excel
1 HSSFWorkbook hssfworkbook = new HSSFWorkbook(); 2 ISheet sheet = hssfworkbook.CreateSheet("我的第一个sheet"); 3 IRow rowheader = sheet.CreateRow(0); 4 rowheader.CreateCell(0, CellType.STRING).SetCellValue("我爱你中国"); 5 IRow row1 = sheet.CreateRow(1); 6 row1.CreateCell(1, CellType.STRING).SetCellValue("012345678901230"); 7 using (Stream stream = File.OpenWrite(path)) 8 { 9 hssfworkbook.Write(stream); 10 }
笨拙的读取Excel
1 using (Stream stream = File.OpenRead(path)) 2 { 3 HSSFWorkbook hssfworkbook = new HSSFWorkbook(stream); 4 ISheet sheet = hssfworkbook.GetSheetAt(0); 5 IRow rowherder = sheet.GetRow(0); 6 DataTable dt = new DataTable(); 7 foreach (ICell cell in rowherder) 8 { 9 dt.Columns.Add(cell.ToString()); 10 } 11 for (int i = sheet.FirstRowNum + 1; i < sheet.LastRowNum; i++) 12 { 13 IRow row = sheet.GetRow(i); 14 DataRow dr = dt.NewRow(); 15 for (int j = 0; j < row.LastCellNum; j++) 16 { 17 dr[j] = row.GetCell(j).ToString(); 18 } 19 dt.Rows.Add(dr); 20 } 21 //Console.WriteLine("读取的excel到DataTable dt"); 22 }