POI处理excel

需要包:

  poi-3.9-20121203.jar

  poi-ooxml-3.9-20121203.jar

  poi-ooxml-schemas-3.9-20121203.jar

  xbean.jar

代码

  1 package com.keertech.miis.news.action;
  2 
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.InputStream;
  6 import java.math.BigDecimal;
  7 import java.util.ArrayList;
  8 import java.util.List;
  9 
 10 import org.apache.commons.lang.StringUtils;
 11 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 12 import org.apache.poi.ss.usermodel.Cell;
 13 import org.apache.poi.ss.usermodel.CellValue;
 14 import org.apache.poi.ss.usermodel.DateUtil;
 15 import org.apache.poi.ss.usermodel.FormulaEvaluator;
 16 import org.apache.poi.ss.usermodel.Row;
 17 import org.apache.poi.ss.usermodel.Sheet;
 18 import org.apache.poi.ss.usermodel.Workbook;
 19 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 20 import org.apache.struts2.ServletActionContext;
 21 
 22 import com.keertech.base.action.JSONAction;
 23 import com.keertech.miis.news.bean.News;
 24 import com.keertech.miis.news.bean.NewsType;
 25 
 26 @SuppressWarnings("serial")
 27 public class MainPageAction extends JSONAction{
 28     
 29     private final String directoryPath = ServletActionContext.getServletContext().getInitParameter("filedirectory")+"/mainPageFile";
 30     
 31     public String turnToMainPage() throws Exception{
 32         
 33 //        List<NewsType> newsTypes = dao.findAll(NewsType.class, " order by createddate desc Fetch First 5 Rows Only");
 34         List<NewsType> newsTypes = (List<NewsType>)dao.findListBySql("select * from miis_news_type order by createddate desc Fetch First 5 Rows Only",null,null);
 35         
 36         String filterString = "";
 37         List<News> news = dao.findAll(News.class, filterString);
 38         
 39         List<List<String>> excelInfo = readExcel();
 40         System.out.println(excelInfo.size());
 41         
 42         request.setAttribute("newsTypes", newsTypes);
 43         request.setAttribute("newses", news);
 44         return SUCCESS;
 45     }
 46     
 47     private List<List<String>> readExcel() throws Exception{
 48         List<List<String>> result = new ArrayList<List<String>>();
 49         InputStream input = null;    //excel输入流
 50         try {
 51             String webPath = request.getSession().getServletContext().getRealPath("/");    //web项目部署的实际物理地址E:/tomcat/webapps/em/
 52             String fullPath = webPath+directoryPath;
 53             File directory = new File(fullPath);
 54             
 55             if (directory.isDirectory()) {
 56                 System.out.println(fullPath);
 57                 File files[] = directory.listFiles();
 58                 
 59                 Workbook workbook = null;    //excel工作簿
 60                 File excelFile = null ;
 61                 String excelFileName = null;
 62                 String separator = null;
 63                 for (File file : files) {
 64                     excelFileName = file.getName();
 65                     Integer separatorIndex = excelFileName.lastIndexOf(".");//获取扩展名所在位置
 66                     separator = excelFileName.substring(separatorIndex);//扩展名
 67                     if(".xls".equals(separator)||".xlsx".equals(separator)) {
 68                         excelFile = file;
 69                         input = new FileInputStream(file);
 70                         break;
 71                     } 
 72                 }
 73                 //生成excel表格对象
 74                 if (excelFile == null) {
 75                     throw new Exception("无法获取当前excel表格");
 76                 }
 77                 if(".xls".equals(separator)) {
 78                     workbook = new HSSFWorkbook(input);
 79                 } else {
 80                     workbook = new XSSFWorkbook(input);
 81                 }
 82                 
 83                 //解析工作表
 84                 for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
 85                     Sheet sheet = workbook.getSheetAt(i);
 86                     if( sheet != null ){
 87                         for (int j = 5; j <= sheet.getLastRowNum(); j++) {
 88                             Row row = sheet.getRow(j);    //获取excel行信息
 89                             List<String> rowList = null;
 90                             if( row != null ){
 91                                 rowList = new ArrayList<String>();
 92                                 int cellNumber = row.getPhysicalNumberOfCells();
 93                                 //将列数据装载到list中
 94                                 for (int k = 0; k < cellNumber; k++) {
 95                                     String cellValue = getCellValue(workbook,row.getCell(k)).toString();
 96                                     if (StringUtils.isNotBlank(cellValue)) {
 97                                         rowList.add(cellValue);
 98                                     }
 99                                 }
100                                 result.add(rowList);
101                             }else {
102                                 continue;
103                             }
104                         }
105                     }
106                 }
107             }
108             
109         } catch (Exception e) {
110             e.printStackTrace();
111             throw new Exception(e.getMessage());
112         } finally{
113             if(input!=null){
114                 input.close();
115             }
116         }
117         return result;
118     }
119     
120     /**
121      * 获取单元格值
122      * @param wb
123      * @param cell
124      * @return
125      */
126     protected Object getCellValue(Workbook wb,Cell cell) {
127         Object result = "";
128         if(cell!=null){
129             switch (cell.getCellType()){
130                 case Cell.CELL_TYPE_STRING:
131                     result =  cell.getStringCellValue().trim();
132                     break;
133                 case Cell.CELL_TYPE_NUMERIC:
134                     if (DateUtil.isCellDateFormatted(cell)){
135                         result = cell.getDateCellValue();
136                     } else {
137                         long longData = (long)cell.getNumericCellValue();
138                         if(longData == cell.getNumericCellValue()){
139                             result = String.valueOf(longData).trim();
140                         }else{
141                             result = String.valueOf(cell.getNumericCellValue()).trim();
142                         }
143                     }
144                     break;
145                 case Cell.CELL_TYPE_FORMULA:    //处理公式
146                     //cell.setCellFormula(cell.getCellFormula());
147                     FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();  
148                     CellValue cellValue = evaluator.evaluate(cell);  
149                     //BigDecimal bigDecimal = new BigDecimal(cell.getCachedFormulaResultType());
150                     BigDecimal bigDecimal = new BigDecimal(cellValue.getNumberValue());
151                     //截取2位小数
152                     result = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).toString().trim();
153                     break;
154                 case Cell.CELL_TYPE_BOOLEAN:
155                     result = cell.getBooleanCellValue();
156                     break;
157                 default:
158                     break;
159             }
160         }
161         return result;
162     }
163 }

 

posted on 2014-08-18 18:39  看天空的星星  阅读(272)  评论(0编辑  收藏  举报

导航