javaWeb使用POI操作Excel

1.为项目添加POI

POI官网链接

点进去之后下载(上边的是编译好的类,下边的是源代码)

 解压文件夹,把下面三个文件复制到WebComtent>WEB-INF>lib文件夹下

再把这三个文件复制到Tomcat的lib文件夹下,否则Tomcat会因为找不到类而报错(这个地方郁闷了一上午)

读取“.xls”格式使用  import org.apache.poi.hssf.usermodel.*;包的内容,例如:HSSFWorkbook
读取“.xlsx”格式使用 import org.apache.poi.xssf.usermodel.*; 包的内容,例如:XSSFWorkbook
读取两种格式使用    import org.apache.poi.ss.usermodel.*    包的内容,例如:Workbook

由于我是读取xslx文件所以使用以上几个jar文件。

注意:

上图中的两个文件夹中也有我们需要的jar文件,具体是哪几个忘记了(当然为了保险也可以把所有的都放进WebContent>WEN-INF>lib下再BuildPath进项目),没关系,一会运行的过程中会报错,根据错误信息再去找到相关的jar文件BuildPath进去就好,注意还要再Tomcat>lib下放置一份副本。

2.读取Excel文件

官方教程:链接

类库:链接 

直接看代码吧,不难懂。

//遍历一个Excel文件
private void getExcelData(File file) { System.out.println("now in getExcelData" ); System.out.println("get file name:"+file.getName().toString()); XSSFWorkbook workBook= null; try { workBook = new XSSFWorkbook(file); int sheetCount = workBook.getNumberOfSheets(); //Sheet的数量 System.out.println("num of sheet is : "+sheetCount); //遍历每个sheet for(int i=0;i<sheetCount;i++) { XSSFSheet sheet = workBook.getSheetAt(i); //获取总行数 int rowCount = sheet.getPhysicalNumberOfRows(); System.out.println("num of row : "+ rowCount); System.out.println("i now in sheet : "+ i); //遍历每一行 for (int r = 0; r < rowCount; r++) { XSSFRow row = sheet.getRow(r); //获取总列数 int cellCount = row.getPhysicalNumberOfCells(); //遍历每一列 for (int c = 0; c < cellCount; c++) { XSSFCell cell = row.getCell(c); String cellValue = null; switch (cell.getCellTypeEnum()) { case STRING: //System.out.println("celltype is string"); cellValue = cell.getStringCellValue(); break; case NUMERIC: //System.out.println("celltype is Number");//整数,小数,日期 cellValue = String.valueOf(cell.getNumericCellValue()); break; case BOOLEAN: //System.out.println("celltype is Boolean"); cellValue = String.valueOf(cell.getBooleanCellValue()); break; case FORMULA: //System.out.println("celltype is Formula");//公式 cellValue = "错误,不能为公式"; break; case BLANK: //System.out.println("celltype is Blank");//空白 cellValue = cell.getStringCellValue(); break; case ERROR: //System.out.println("celltype is Error"); cellValue = "错误"; break; default: //System.out.println("celltype : default"); cellValue = "错误"; break; } System.out.println(cellValue.toString()); } } } } catch (IOException e) { System.out.println("File Error IOException : "+e.getMessage()); } catch (Exception e) { // TODO: handle exception } finally { try { workBook.close();    } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("workBook.close()&fileInputStream.close() Error : "+e.getMessage()); } System.out.println("Try Catch : finally"); } System.out.println("hi feipeng8848 getExcelData is done"); }

  

原文地址:https://www.cnblogs.com/feipeng8848/p/6781822.html