标签:
1、整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表):Sheet;行:Row;单元格Cell。
2、NPOI是POI的C#版本,NPOI的行和列的index都是从0开始
3、POI读取Excel有两种格式一个是HSSF,另一个是XSSF。
HSSF和XSSF的区别如下:
HSSF is the POI Project‘s pure Java implementation of the Excel ‘97(-2007) file format.
XSSF is the POI Project‘s pure Java implementation of the Excel 2007 OOXML (.xlsx) file format.
即:HSSF适用2007以前的版本,XSSF适用2007版本及其以上的。
DataTable dt = new DataTable(); HSSFWorkbook hssfworkbook = null; //HSSF适用2007以前的版本 XSSFWorkbook xssfworkbook = null; //XSSF适用2007版本及其以上的。 //string fileExt = Path.GetExtension(strFileName);//获取文件的后缀名 using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { if (fileType == ".xls") hssfworkbook = new HSSFWorkbook(file); else if (fileType == ".xlsx") xssfworkbook = new XSSFWorkbook(file);//初始化太慢了,不知道这是什么bug } if (hssfworkbook != null) { HSSFSheet sheet = (HSSFSheet)hssfworkbook.GetSheet("Manifest"); if (sheet != null) { System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); HSSFRow headerRow = (HSSFRow)sheet.GetRow(5); int cellCount = headerRow.LastCellNum; for (int j = 0; j < cellCount; j++) { HSSFCell cell = (HSSFCell)headerRow.GetCell(j); dt.Columns.Add(Convert.ToString(cell)); } for (int i = 6; i <= sheet.LastRowNum; i++) { HSSFRow row = (HSSFRow)sheet.GetRow(i); DataRow dataRow = dt.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++) { var aa = row.GetCell(j); if (row.GetCell(j)!=null) dataRow[j] =Convert.ToString(row.GetCell(j)); } dt.Rows.Add(dataRow); } } } else if (xssfworkbook != null) { XSSFSheet xSheet = (XSSFSheet)xssfworkbook.GetSheet("Manifest"); if (xSheet != null) { System.Collections.IEnumerator rows = xSheet.GetRowEnumerator(); XSSFRow headerRow = (XSSFRow)xSheet.GetRow(0); int cellCount = headerRow.LastCellNum; for (int j = 0; j < cellCount; j++) { XSSFCell cell = (XSSFCell)headerRow.GetCell(j); dt.Columns.Add(cell.ToString()); } for (int i = (xSheet.FirstRowNum + 1); i <= xSheet.LastRowNum; i++) { XSSFRow row = (XSSFRow)xSheet.GetRow(i); DataRow dataRow = dt.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) dataRow[j] = row.GetCell(j).ToString(); } dt.Rows.Add(dataRow); } } }
标签:
原文地址:http://www.cnblogs.com/wlwenjie/p/4530656.html