zoukankan      html  css  js  c++  java
  • Java POI导入Excel文件

      今天在公司需要做个导入Excel文件的功能,所以研究了一下,参考网上的一些资料总算是做出来了,在此记录一下防止以后忘记怎么弄。

      本人用的是poi3.8,所以需要的JAR包如下:

        poi-3.8.jar 

        poi-excelant-3.8-20120326.jar

        poi-ooxml-3.8-20120326.jar

        poi-ooxml-schemas-3.8-20120326.jar

        poi-scratchpad-3.8-20120326.jar

        xmlbeans-2.3.0.jar

      附上百度云盘的共享地址,JAR包来自apache官方:http://pan.baidu.com/s/1bnzzheR

      附上方法详情,方法来自csdn的一个博客,具体地址我给忘了,反正不是原创,不过在其基础上修改了下,代码更易读,为了让第一次做这个的人弄明白,所以注释部分写的详细了一些,实际用的时候可以删掉,此方法可以兼容xls和xlsx两种格式,其他的未经过测试:

    public String importExcel() {
    		try{
    			InputStream inputStream = new FileInputStream("C:\Users\Administrator\Desktop\test.xls");
    			//根据输入流获取工作簿(整个excel文件)
    			Workbook workbook = WorkbookFactory.create(inputStream);
    			//获取第一个工作表(excel文件中第一个工作表)
    			Sheet sheet = workbook.getSheetAt(0);
    			//获取行迭代器
    			Iterator<Row> rowIterator = sheet.rowIterator();
    			while(rowIterator.hasNext()){
    				//获取当前行
    				Row row = (Row) rowIterator.next();
    				//获取单元格迭代器
    				Iterator<Cell> colIterator = row.cellIterator(); 
    				while (colIterator.hasNext()){
    					//获取当前单元格
    					Cell cell = (Cell) colIterator.next();
    					//打印列号和行号,从0开始,Excel中A1单元格打印出来是0:0,B2单元格打印出来是1:1
    					System.out.print(cell.getRowIndex() + ":" + cell.getColumnIndex() + " ");
    					//根据单元格的数据类型获取数据
    					switch (cell.getCellType()){
    						case Cell.CELL_TYPE_STRING:
    							System.out.println(cell.getRichStringCellValue().getString());
    							break;
    						case Cell.CELL_TYPE_NUMERIC:
    							if (DateUtil.isCellDateFormatted(cell)){
    								System.out.println(cell.getDateCellValue());
    							}else{
    								System.out.println(cell.getNumericCellValue());
    							}
    							break;
    						case Cell.CELL_TYPE_BOOLEAN:
    							System.out.println(cell.getBooleanCellValue());
    							break;
    						case Cell.CELL_TYPE_FORMULA:
    							System.out.println(cell.getCellFormula());
    							break;
    						default:
    							System.out.println("null");
    					}
    				}
    			}
    		} catch (Exception e){
    			e.printStackTrace();
    		}
    		return "";
    	}
    
  • 相关阅读:
    反向代理实例
    nginx常用命令和配置
    nginx的安装
    Can Live View boot up images acquired from 64bit OS evidence?
    What is the behavior of lnk files?
    EnCase v7 search hits in compound files?
    How to search compound files
    iOS 8.3 JB ready
    Sunglasses
    现代福尔摩斯
  • 原文地址:https://www.cnblogs.com/aotian/p/4556945.html
Copyright © 2011-2022 走看看