zoukankan      html  css  js  c++  java
  • poi读取excel内容工具类

    该工具类可以读取excel2007,excel2003等格式的文件,xls、xlsx文件格式

      1 package com.visolink;
      2 
      3 import org.apache.poi.hssf.usermodel.*;
      4 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
      5 import org.apache.poi.ss.usermodel.Cell;
      6 import org.apache.poi.ss.usermodel.Row;
      7 import org.apache.poi.ss.usermodel.Sheet;
      8 import org.apache.poi.ss.usermodel.Workbook;
      9 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
     10 
     11 import java.io.*;
     12 import java.text.SimpleDateFormat;
     13 import java.util.Date;
     14 import java.util.HashMap;
     15 import java.util.Map;
     16 import java.util.Set;
     17 
     18 public class ExcelReader {
     19     private POIFSFileSystem fs;
     20     private Workbook wb;
     21     private Sheet sheet;
     22     private Row row;
     23 
     24 
     25     /**
     26      * 读取Excel表格表头的内容
     27      * @param file
     28      * @return String 表头内容的数组
     29      */
     30     public String[] readExcelTitle(File file) {
     31         try {
     32             InputStream is=new FileInputStream(file);
     33 
     34             if(file.getName().toLowerCase().endsWith(".xls")){
     35                 fs = new POIFSFileSystem(is);
     36                 wb = new HSSFWorkbook(fs);
     37             }
     38             else{
     39                 wb=new XSSFWorkbook(is);
     40             }
     41         } catch (IOException e) {
     42             e.printStackTrace();
     43         }
     44         sheet = wb.getSheetAt(0);
     45         row = sheet.getRow(0);
     46         // 标题总列数
     47         int colNum = row.getPhysicalNumberOfCells();
     48         System.out.println("colNum:" + colNum);
     49         String[] title = new String[colNum];
     50         for (int i = 0; i < colNum; i++) {
     51             //title[i] = getStringCellValue(row.getCell((short) i));
     52             title[i] = getCellFormatValue(row.getCell((short) i));
     53         }
     54         return title;
     55     }
     56 
     57     /**
     58      * 读取Excel数据内容
     59      * @param file
     60      * @return Map 包含单元格数据内容的Map对象
     61      */
     62     public Map<Integer, String> readExcelContent(File file) {
     63         Map<Integer, String> content = new HashMap<Integer, String>();
     64         String str = "";
     65         try {
     66             InputStream is=new FileInputStream(file);
     67             if(file.getName().toLowerCase().endsWith(".xls")){
     68                 //fs = new POIFSFileSystem(is);
     69                 wb = new HSSFWorkbook(is);
     70             }else{
     71                 wb=new XSSFWorkbook(is);
     72             }
     73 
     74         } catch (IOException e) {
     75             e.printStackTrace();
     76         }
     77         sheet = wb.getSheetAt(0);
     78         // 得到总行数
     79         int rowNum = sheet.getLastRowNum();
     80         row = sheet.getRow(0);
     81         int colNum = row.getPhysicalNumberOfCells();
     82         // 正文内容应该从第二行开始,第一行为表头的标题
     83         for (int i = 1; i <= rowNum; i++) {
     84             row = sheet.getRow(i);
     85             int j = 0;
     86             while (j < colNum) {
     87                 // 每个单元格的数据内容用"-"分割开,以后需要时用String类的replace()方法还原数据
     88                 // 也可以将每个单元格的数据设置到一个javabean的属性中,此时需要新建一个javabean
     89                 // str += getStringCellValue(row.getCell((short) j)).trim() +
     90                 // "-";
     91                 str += getCellFormatValue(row.getCell((short) j)).trim() + "    ";
     92                 j++;
     93             }
     94             content.put(i, str);
     95             str = "";
     96         }
     97         return content;
     98     }
     99 
    100     /**
    101      * 获取单元格数据内容为字符串类型的数据
    102      *
    103      * @param cell Excel单元格
    104      * @return String 单元格数据内容
    105      */
    106     private String getStringCellValue(HSSFCell cell) {
    107         String strCell = "";
    108         switch (cell.getCellType()) {
    109             case HSSFCell.CELL_TYPE_STRING:
    110                 strCell = cell.getStringCellValue();
    111                 break;
    112             case HSSFCell.CELL_TYPE_NUMERIC:
    113                 strCell = String.valueOf(cell.getNumericCellValue());
    114                 break;
    115             case HSSFCell.CELL_TYPE_BOOLEAN:
    116                 strCell = String.valueOf(cell.getBooleanCellValue());
    117                 break;
    118             case HSSFCell.CELL_TYPE_BLANK:
    119                 strCell = "";
    120                 break;
    121             default:
    122                 strCell = "";
    123                 break;
    124         }
    125         if (strCell.equals("") || strCell == null) {
    126             return "";
    127         }
    128         if (cell == null) {
    129             return "";
    130         }
    131         return strCell;
    132     }
    133 
    134     /**
    135      * 获取单元格数据内容为日期类型的数据
    136      *
    137      * @param cell
    138      *            Excel单元格
    139      * @return String 单元格数据内容
    140      */
    141     private String getDateCellValue(HSSFCell cell) {
    142         String result = "";
    143         try {
    144             int cellType = cell.getCellType();
    145             if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
    146                 Date date = cell.getDateCellValue();
    147                 result = (date.getYear() + 1900) + "-" + (date.getMonth() + 1)
    148                         + "-" + date.getDate();
    149             } else if (cellType == HSSFCell.CELL_TYPE_STRING) {
    150                 String date = getStringCellValue(cell);
    151                 result = date.replaceAll("[年月]", "-").replace("日", "").trim();
    152             } else if (cellType == HSSFCell.CELL_TYPE_BLANK) {
    153                 result = "";
    154             }
    155         } catch (Exception e) {
    156             System.out.println("日期格式不正确!");
    157             e.printStackTrace();
    158         }
    159         return result;
    160     }
    161 
    162     /**
    163      * 根据HSSFCell类型设置数据
    164      * @param cell
    165      * @return
    166      */
    167     private String getCellFormatValue(Cell cell) {
    168         String cellvalue = "";
    169         if (cell != null) {
    170             // 判断当前Cell的Type
    171             switch (cell.getCellType()) {
    172                 // 如果当前Cell的Type为NUMERIC
    173                 case HSSFCell.CELL_TYPE_NUMERIC:
    174                 case HSSFCell.CELL_TYPE_FORMULA: {
    175                     // 判断当前的cell是否为Date
    176                     if (HSSFDateUtil.isCellDateFormatted(cell)) {
    177                         // 如果是Date类型则,转化为Data格式
    178 
    179                         //方法1:这样子的data格式是带时分秒的:2011-10-12 0:00:00
    180                         //cellvalue = cell.getDateCellValue().toLocaleString();
    181 
    182                         //方法2:这样子的data格式是不带带时分秒的:2011-10-12
    183                         Date date = cell.getDateCellValue();
    184                         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    185                         cellvalue = sdf.format(date);
    186 
    187                     }
    188                     // 如果是纯数字
    189                     else {
    190                         // 取得当前Cell的数值
    191                         cellvalue = String.valueOf(cell.getNumericCellValue());
    192                     }
    193                     break;
    194                 }
    195                 // 如果当前Cell的Type为STRIN
    196                 case HSSFCell.CELL_TYPE_STRING:
    197                     // 取得当前的Cell字符串
    198                     cellvalue = cell.getRichStringCellValue().getString();
    199                     break;
    200                 // 默认的Cell值
    201                 default:
    202                     cellvalue = " ";
    203             }
    204         } else {
    205             cellvalue = "";
    206         }
    207         return cellvalue;
    208 
    209     }
    210 
    211     public static void main(String[] args) {
    212 
    213         try {
    214 
    215             System.out.println("开始");
    216             File file=new File("D:\用户列表测试.xlsx");
    217             ExcelReader er=new ExcelReader();
    218             String [] titles=er.readExcelTitle(file);
    219             for(String title:titles){
    220                 System.out.println(title);
    221             }
    222 
    223             Map<Integer,String>   contents= er.readExcelContent(file);
    224             Set<Integer> contentsKey=contents.keySet();
    225             for(Integer key:contentsKey){
    226                 System.out.println("第"+key+"行:"+contents.get(key));
    227             }
    228 
    229         }catch(Exception e){
    230 
    231             e.getMessage();
    232         }
    233     }
    234 }
  • 相关阅读:
    1219 总结
    1206 冲刺三
    1130 冲刺2
    1128 主页面
    1123 冲刺3
    1121 冲刺2
    1118 冲刺1
    1117 新冲刺
    0622 软件工程总结
    0617 实验四 主存空间的分配和回收
  • 原文地址:https://www.cnblogs.com/git-niu/p/7877779.html
Copyright © 2011-2022 走看看