Apache POI解析excel文件

这里需要用到poi.jar和poi-ooxml.jar  没有的可以去http://mvnrepository.com/下载

  1 import org.apache.poi.POIXMLDocument;
  2 import org.apache.poi.hssf.usermodel.HSSFDateUtil;
  3 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  4 import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  5 import org.apache.poi.openxml4j.opc.OPCPackage;
  6 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  7 import org.apache.poi.ss.usermodel.Cell;
  8 import org.apache.poi.ss.usermodel.Row;
  9 import org.apache.poi.ss.usermodel.Sheet;
 10 import org.apache.poi.ss.usermodel.Workbook;
 11 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 12 
 13 import java.io.FileInputStream;
 14 import java.io.IOException;
 15 import java.io.InputStream;
 16 import java.io.PushbackInputStream;
 17 import java.text.SimpleDateFormat;
 18 import java.util.*;
 19 
 20 /**
 21  * Created by Donge on 2017/1/3.
 22  */
 23 public class ReadExcel {
 24 
 25     static private Workbook wb;
 26     static private Sheet sheet;
 27     static private Row row;
 28 
 29     /**
 30      * 读取 Excel 标题
 31      * @param fileName
 32      * @return
 33      */
 34     public static String[] readExcelTitle(String fileName) {
 35         try {
 36             wb = createWorkbook(new FileInputStream(fileName));
 37         } catch (IOException e) {
 38             e.printStackTrace();
 39         } catch (InvalidFormatException e) {
 40             e.printStackTrace();
 41         }
 42         sheet = wb.getSheetAt(0);
 43         row = sheet.getRow(0);// 获取第一行(约定第一行是标题行)
 44         int colNum = row.getLastCellNum();// 获取行的列数
 45         String[] titles = new String[colNum];
 46         for (int i = 0; i < titles.length; i++) {
 47             titles[i] = getCellFormatValue(row.getCell(i));
 48         }
 49         return titles;
 50     }
 51 
 52     /**
 53      * 读取 Excel 内容
 54      * @param fileName
 55      * @return
 56      */
 57     public static List<Map<String, String>> readExcelContent(String fileName) {
 58         List<Map<String, String>> list = new ArrayList<>();
 59         Map<String, String> content;
 60         try {
 61             wb = createWorkbook(new FileInputStream(fileName));
 62         } catch (IOException e) {
 63             e.printStackTrace();
 64         } catch (InvalidFormatException e) {
 65             e.printStackTrace();
 66         }
 67         sheet = wb.getSheetAt(0);
 68         int rowNum = sheet.getLastRowNum()+1;// 得到总行数
 69         row = sheet.getRow(0);
 70         int colNum = row.getLastCellNum();// 得到总列数
 71         String titles[] = readExcelTitle(fileName);
 72         // 正文内容应该从第二行开始,第一行为表头的标题
 73         for (int i = 1; i < rowNum; i++) {
 74             int j = 0;
 75             row = sheet.getRow(i);
 76             content = new LinkedHashMap<>();
 77             do {
 78                 content.put(titles[j], getCellFormatValue(row.getCell(j)).trim());
 79                 j++;
 80             } while (j < colNum);
 81             list.add(content);
 82         }
 83         return list;
 84     }
 85 
 86     /**
 87      * 根据Cell类型设置数据
 88      * @param cell
 89      * @return
 90      */
 91     private static String getCellFormatValue(Cell cell) {
 92         String cellValue = " ";
 93         if (cell != null) {
 94             // 判断当前Cell的Type
 95             switch (cell.getCellType()) {
 96                 // 如果当前Cell的Type为NUMERIC
 97                 case Cell.CELL_TYPE_NUMERIC:
 98                 case Cell.CELL_TYPE_FORMULA: {
 99                     // 判断当前的cell是否为Date
100                     if (HSSFDateUtil.isCellDateFormatted(cell)) {
101                         Date date = cell.getDateCellValue();
102                         cellValue = new SimpleDateFormat("yyyy-MM-dd").format(date);// 时间格式化显示:2012-12-31
103                     } else {
104                         // 如果是纯数字取得当前Cell的数值
105                         cellValue = String.valueOf(cell.getNumericCellValue());
106                     }
107                     break;
108                 }
109                 // 如果当前Cell的Type为STRIN
110                 case Cell.CELL_TYPE_STRING:
111                     cellValue = cell.getRichStringCellValue().getString();
112                     break;
113                 default:
114                     // 默认的Cell值
115                     cellValue = " ";
116             }
117         }
118         return cellValue;
119 
120     }
121 
122     /**
123      * 创建 Workbook
124      * @param is
125      * @return
126      * @throws IOException
127      * @throws InvalidFormatException
128      */
129     public static Workbook createWorkbook(InputStream is) throws IOException,InvalidFormatException {
130         if (!is.markSupported()) {
131             is = new PushbackInputStream(is, 8);
132         }
133         if (POIFSFileSystem.hasPOIFSHeader(is)) {
134             return new HSSFWorkbook(is);
135         }
136         if (POIXMLDocument.hasOOXMLHeader(is)) {
137             return new XSSFWorkbook(OPCPackage.open(is));
138         }
139         throw new IllegalArgumentException("POI解析不了您当前的Excel版本");
140     }
141 
142     /**
143      * 测试
144      * @param args
145      */
146     public static void main(String args[]) {
147         String filePath = "D:\\Test.xls";
148         List<Map<String, String>> list = readExcelContent(filePath);
149         Map<String, String> map;
150         for (int i = 0; i < list.size(); i++) {
151             map = list.get(i);
152             System.out.println("**************THE START OF ROW("+(i+1)+")**************");
153             for (String key : map.keySet()) {
154                 System.out.println(key + " : " + map.get(key));
155             }
156         }
157     }
158 }

 

posted @ 2017-01-03 16:46  Qingdong.Li  Views(291)  Comments(1Edit  收藏  举报