Excel解析

  1. import java.io.FileInputStream;  
  2. import java.io.FileNotFoundException;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.util.Date;  
  6. import java.util.HashMap;  
  7. import java.util.Map;  
  8.   
  9. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  10. import org.apache.poi.ss.usermodel.Cell;  
  11. import org.apache.poi.ss.usermodel.DateUtil;  
  12. import org.apache.poi.ss.usermodel.Row;  
  13. import org.apache.poi.ss.usermodel.Sheet;  
  14. import org.apache.poi.ss.usermodel.Workbook;  
  15. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  16. import org.slf4j.Logger;  
  17. import org.slf4j.LoggerFactory;  
  18.   
  19. /** 
  20.  * 读取Excel 
  21.  *  
  22.  * @author zengwendong 
  23.  */  
  24. public class ReadExcelUtils {  
  25.     private Logger logger = LoggerFactory.getLogger(ReadExcelUtils.class);  
  26.     private Workbook wb;  
  27.     private Sheet sheet;  
  28.     private Row row;  
  29.   
  30.     public ReadExcelUtils(String filepath) {  
  31.         if(filepath==null){  
  32.             return;  
  33.         }  
  34.         String ext = filepath.substring(filepath.lastIndexOf("."));  
  35.         try {  
  36.             InputStream is = new FileInputStream(filepath);  
  37.             if(".xls".equals(ext)){  
  38.                 wb = new HSSFWorkbook(is);  
  39.             }else if(".xlsx".equals(ext)){  
  40.                 wb = new XSSFWorkbook(is);  
  41.             }else{  
  42.                 wb=null;  
  43.             }  
  44.         } catch (FileNotFoundException e) {  
  45.             logger.error("FileNotFoundException", e);  
  46.         } catch (IOException e) {  
  47.             logger.error("IOException", e);  
  48.         }  
  49.     }  
  50.       
  51.     /** 
  52.      * 读取Excel表格表头的内容 
  53.      *  
  54.      * @param InputStream 
  55.      * @return String 表头内容的数组 
  56.      * @author zengwendong 
  57.      */  
  58.     public String[] readExcelTitle() throws Exception{  
  59.         if(wb==null){  
  60.             throw new Exception("Workbook对象为空!");  
  61.         }  
  62.         sheet = wb.getSheetAt(0);  
  63.         row = sheet.getRow(0);  
  64.         // 标题总列数  
  65.         int colNum = row.getPhysicalNumberOfCells();  
  66.         System.out.println("colNum:" + colNum);  
  67.         String[] title = new String[colNum];  
  68.         for (int i = 0; i < colNum; i++) {  
  69.             // title[i] = getStringCellValue(row.getCell((short) i));  
  70.             title[i] = row.getCell(i).getCellFormula();  
  71.         }  
  72.         return title;  
  73.     }  
  74.   
  75.     /** 
  76.      * 读取Excel数据内容 
  77.      *  
  78.      * @param InputStream 
  79.      * @return Map 包含单元格数据内容的Map对象 
  80.      * @author zengwendong 
  81.      */  
  82.     public Map<Integer, Map<Integer,Object>> readExcelContent() throws Exception{  
  83.         if(wb==null){  
  84.             throw new Exception("Workbook对象为空!");  
  85.         }  
  86.         Map<Integer, Map<Integer,Object>> content = new HashMap<Integer, Map<Integer,Object>>();  
  87.           
  88.         sheet = wb.getSheetAt(0);  
  89.         // 得到总行数  
  90.         int rowNum = sheet.getLastRowNum();  
  91.         row = sheet.getRow(0);  
  92.         int colNum = row.getPhysicalNumberOfCells();  
  93.         // 正文内容应该从第二行开始,第一行为表头的标题  
  94.         for (int i = 1; i <= rowNum; i++) {  
  95.             row = sheet.getRow(i);  
  96.             int j = 0;  
  97.             Map<Integer,Object> cellValue = new HashMap<Integer, Object>();  
  98.             while (j < colNum) {  
  99.                 Object obj = getCellFormatValue(row.getCell(j));  
  100.                 cellValue.put(j, obj);  
  101.                 j++;  
  102.             }  
  103.             content.put(i, cellValue);  
  104.         }  
  105.         return content;  
  106.     }  
  107.   
  108.     /** 
  109.      *  
  110.      * 根据Cell类型设置数据 
  111.      *  
  112.      * @param cell 
  113.      * @return 
  114.      * @author zengwendong 
  115.      */  
  116.     private Object getCellFormatValue(Cell cell) {  
  117.         Object cellvalue = "";  
  118.         if (cell != null) {  
  119.             // 判断当前Cell的Type  
  120.             switch (cell.getCellType()) {  
  121.             case Cell.CELL_TYPE_NUMERIC:// 如果当前Cell的Type为NUMERIC  
  122.             case Cell.CELL_TYPE_FORMULA: {  
  123.                 // 判断当前的cell是否为Date  
  124.                 if (DateUtil.isCellDateFormatted(cell)) {  
  125.                     // 如果是Date类型则,转化为Data格式  
  126.                     // data格式是带时分秒的:2013-7-10 0:00:00  
  127.                     // cellvalue = cell.getDateCellValue().toLocaleString();  
  128.                     // data格式是不带带时分秒的:2013-7-10  
  129.                     Date date = cell.getDateCellValue();  
  130.                     cellvalue = date;  
  131.                 } else {// 如果是纯数字  
  132.   
  133.                     // 取得当前Cell的数值  
  134.                     cellvalue = String.valueOf(cell.getNumericCellValue());  
  135.                 }  
  136.                 break;  
  137.             }  
  138.             case Cell.CELL_TYPE_STRING:// 如果当前Cell的Type为STRING  
  139.                 // 取得当前的Cell字符串  
  140.                 cellvalue = cell.getRichStringCellValue().getString();  
  141.                 break;  
  142.             default:// 默认的Cell值  
  143.                 cellvalue = "";  
  144.             }  
  145.         } else {  
  146.             cellvalue = "";  
  147.         }  
  148.         return cellvalue;  
  149.     }  
  150.   
  151.     public static void main(String[] args) {  
  152.         try {  
  153.             String filepath = "F:test.xls";  
  154.             ReadExcelUtils excelReader = new ReadExcelUtils(filepath);  
  155.             // 对读取Excel表格标题测试  
  156. //          String[] title = excelReader.readExcelTitle();  
  157. //          System.out.println("获得Excel表格的标题:");  
  158. //          for (String s : title) {  
  159. //              System.out.print(s + " ");  
  160. //          }  
  161.               
  162.             // 对读取Excel表格内容测试  
  163.             Map<Integer, Map<Integer,Object>> map = excelReader.readExcelContent();  
  164.             System.out.println("获得Excel表格的内容:");  
  165.             for (int i = 1; i <= map.size(); i++) {  
  166.                 System.out.println(map.get(i));  
  167.             }  
  168.         } catch (FileNotFoundException e) {  
  169.             System.out.println("未找到指定路径的文件!");  
  170.             e.printStackTrace();  
  171.         }catch (Exception e) {  
  172.             e.printStackTrace();  
  173.         }  
  174.     }  

  1. }  
常量说明取值
Cell.CELL_TYPE_NUMERIC数值类型cell.getNumericCellValue()
或cell.getDateCellValue()
Cell.CELL_TYPE_STRING字符串类型cell.getStringCellValue()
或cell.toString()
Cell.CELL_TYPE_BOOLEAN布尔类型cell.getBooleanCellValue()
Cell.CELL_TYPE_FORMULA表达式类型cell.getCellFormula()
Cell.CELL_TYPE_ERROR异常类型
不知道何时算异常
cell.getErrorCellValue()
Cell.CELL_TYPE_BLANK空,不知道何时算空空就不要取值了吧

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值