赞助

java使用POI读取excel报表

留此作为记录

 1 package com.demo;
 2 
 3 import java.io.FileInputStream;
 4 import java.util.Iterator;
 5 
 6 import org.apache.poi.hssf.usermodel.HSSFCell;
 7 import org.apache.poi.hssf.usermodel.HSSFRow;
 8 import org.apache.poi.hssf.usermodel.HSSFSheet;
 9 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
10 
11 public class DemoTest {
12     public static void main(String[] args) {
13         System.out.println(readXls(System.getProperty("user.dir") + "\\case\\副本业务编码大全.xls"));
14     }
15 
16     public static String readXls(String path) {
17         String text = "";
18         try {
19             FileInputStream is = new FileInputStream(path);
20             HSSFWorkbook excel = new HSSFWorkbook(is);
21             // 获取第一个sheet
22             HSSFSheet sheet0 = excel.getSheetAt(0);
23             for (Iterator<?> rowIterator = sheet0.iterator(); rowIterator.hasNext();) {
24                 HSSFRow row = (HSSFRow) rowIterator.next();
25                 for (Iterator<?> iterator = row.cellIterator(); iterator.hasNext();) {
26                     HSSFCell cell = (HSSFCell) iterator.next();
27                     // 根据单元的的类型 读取相应的结果
28                     if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
29                         text += cell.getStringCellValue() + "\t";
30                     else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
31                         text += cell.getNumericCellValue() + "\t";
32                     else if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA)
33                         text += cell.getCellFormula() + "\t";
34                 }
35                 text += "\n";
36             }
37         } catch (Exception e) {
38             // TODO Auto-generated catch block
39             e.printStackTrace();
40         }
41         return text;
42     }
43 }

 

posted @ 2018-05-03 16:42  念念不忘、  阅读(329)  评论(0编辑  收藏  举报