版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhao3587717/article/details/51506686
这些天研究了一下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(); } }
扫描二维码关注公众号,回复:
3660550 查看本文章
5.运行结果。
6.
SmartUpload资源地址:SmartUpload资源地址
Apache Poi资源地址:Apache Poi资源地址