1. 程式人生 > >Servlet + Jsp + Poi 實現 excel 的解析

Servlet + Jsp + Poi 實現 excel 的解析

  這些天研究了一下Apache POI,Apache POI是Apache軟體基金會的開源專案,POI提供API給Java程式對Microsoft Office格式檔案讀和寫的功能。 .NET的開發人員則可以利用NPOI (POI for .NET) 來存取 Microsoft Office文件的功能。

  今天主要介紹一下,如何通過匯入excel,然後進行解析。

  1.首先,新建Web專案。

  2.然後將poi的jar包匯入。如圖

  

  3.ImportExcel.jsp頁面程式碼。

  <body>
    <form action="<%=basePath%>ImportExcel" method="post" enctype="multipart/form-data">
    	<table>
    		<tr>
    			<td>
    				<input type="file" name="file1" size="30"/>
    			</td>
    			<td>
    				<input type="submit" value="提交" />
    			</td>
    		</tr>
    	</table>
    </form>
  </body>
  

  4.Servlet中的程式碼如下。

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { SmartUpload smu = new SmartUpload(); smu.initialize(this.getServletConfig(),request,response); // smu.setAllowedFilesList("gif,jpg,png,bmp"); // smu.setMaxFileSize(100*1024*1024); //單個檔案最大限制為100K smu.setCharset("gbk"); smu.upload(); com.jspsmart.upload.File file = smu.getFiles().getFile(0); String fullpath = file.getFilePathName(); System.out.println(fullpath); InputStream input = new FileInputStream(fullpath); POIFSFileSystem fs = new POIFSFileSystem(input); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); // 迭代sheet中的每一行 Iterator<row> rows = sheet.rowIterator(); while (rows.hasNext()) { HSSFRow row = (HSSFRow) rows.next(); System.out.println("Row #" + row.getRowNum()); // 迭代每一行的cell"s // content Iterator<cell> cells = row.cellIterator(); while (cells.hasNext()) { HSSFCell cell = (HSSFCell) cells.next(); switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_NUMERIC: System.out.println(cell.getNumericCellValue()); break; case HSSFCell.CELL_TYPE_STRING: System.out.println(cell.getStringCellValue()); break; case HSSFCell.CELL_TYPE_BOOLEAN: System.out.println(cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_FORMULA: System.out.println(cell.getCellFormula()); break; default: System.out.println("unsuported sell type"); break; } } } } catch (SmartUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } }

      5.執行結果。

        

     6.

SmartUpload資源地址:SmartUpload資源地址   

Apache Poi資源地址:Apache Poi資源地址