[Java] Java读取、分析excel文件的代码 →→→→→进入此内容的聊天室

来自 , 2020-03-29, 写在 Java, 查看 118 次.
URL http://www.code666.cn/view/03e0704b
  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.     }
  175. }
  176.  
  177. //源代码片段来自云代码http://yuncode.net
  178.                        

回复 "Java读取、分析excel文件的代码"

这儿你可以回复上面这条便签

captcha