解析 excel

第一步:jsp

<form name="form1" method="POST" action="/cooperation/import_excel.do?fileType=excel&cityId=${cityId}" onsubmit="javascript:return excel();"  enctype="multipart/form-data" target="hiddenIframe" >

2003版Excel導入:<input id="file" type="file" name="file"  >

<input id="type" type="hidden" value="2" name="type">

第二步: action

import org.apache.commons.io.FileUtils;

private File file;

private final static String filePre = "/data/homes/ftesitemanage/temp/";

public String import_excel(){

if (excelLock) return null;

try {

excelLock = true;

String activityId=getParameter("excelActivityid");

 

String filePath = "";

   File newFile=null;

   filePath = filePre+System.currentTimeMillis();

if("excel".equals(fileType)){ 

newFile = new File( filePath+".xls");

FileUtils.copyFile(file, newFile);

if(fileimg!=null){

newFile=new File(filePre);

if(!newFile.exists()){

FileUtil.makeParent(newFile);

}

derExcute.unZipFile(fileimg,filePre);

}

if(!"".equals(cooperationService.importExcelCooperation(activityId, filePath+".xls"))){ //說明有分配新短號失敗的經紀人

this.setWriterPrint("<script>parent.showfailSpan('0');</script>");

return null;

}else{

this.setWriterPrint("<script>parent.showfailSpan('1');</script>");

return null;

}

}

} catch (Exception e){

e.printStackTrace();

}finally {

excelLock = false;

}

return null;

}

第三步:ServiceImpl 類

public String importExcelCooperation(String activityId, String filePath) {

String returnValue = "";

try {

if (filePath != null && !"".equals(filePath)) {

List<ArrayList<String>> dataList = CooperationExcelUtil

.read(filePath);

if (dataList.size() > 0) {

//合作活動的經紀人的短號

Map<String,String> numMap = cooperationDao.getCoopeation4008NumByActivityId(Integer.parseInt(activityId));

//獲得此次合作活動能分配的短號

List asignNumList = cooperationDao.getAsignDianxin400Num(9);

System.out.println((dataList.size()) + "行……");

FteCooperationJournal joural = null;

for (ArrayList<String> innerLst : dataList) {

joural = new FteCooperationJournal();

String text = "";

for (int i = 0; i < innerLst.size(); i++) { // 讀取每列的數據

if (innerLst.get(i)==null) continue;

text = innerLst.get(i).trim();

if (StringUtils.isEmpty(text)) continue;

joural.setActivityId(Integer.parseInt(activityId));

if (i == 0) { // 城市

if (innerLst.get(i) != null) {

int cityid=getCityIdByStr(text);

city=cityid==10?"bj":"sh";

joural.setCityId(cityid);

}

}

else if (i == 1) { // 經紀人手機號碼

joural.setPhone(text);

int userid = cooperationDao.getUserIdByPhone(text);

if(userid==0){

continue;

}

if (userid > 0) {

joural.setAgentUserId(userid);

joural.setPhone400(cooperationDao.get400PhoneByUserId());

} else {// 如果經紀人是空號,就不保存此條信息,跳出此條信息

continue;

}

}

else if (i == 2) { // 經紀人姓名

joural.setAgentName(text);

}

else if (i == 3) { // 樓盤名

joural.setEstateName(text);

Map map = cooperationDao.getAreaDataByEstateName(text);

if (map!=null) {

joural.setAreaId(Integer.parseInt(map.get("areaId").toString()));

joural.setSubAreaId(Integer.parseInt(map.get("subAreaId").toString()));

}

}

else if (i == 4) { // 區域

joural.setAreaName(text);

if (joural.getAreaId()==0)

joural.setAreaId(cooperationDao.getAreaIdByAreaName(text));

}

else if (i == 5) { // 商圈

joural.setSubAreaName(text);

if (joural.getSubAreaId()==0)

joural.setSubAreaId(cooperationDao.gerSubAreaIdBySubAreaName(text));

}

else if (i == 6) { // 房源封面圖路徑

if("房源封面圖路徑".equals(text)){

continue;

}

String url = validateUrlToLocal(text,filePath);// 檢查路徑並把圖片下載到本地

joural.setCover(url);

}

else if (i == 7) { // 租售類型(租/售)

joural.setSalesType("租".equals(text) ? "R" : "S");

}

else if (i == 8) { // 租金(元/月)

float weishengjian = 0;

try {

weishengjian = Float.parseFloat(text);

} catch (Exception e) {

weishengjian = 0;

System.out.println("租金(元/月)的數據格式錯誤異常: "+ e.getMessage());

}

joural.setRentPrice(weishengjian);

}

else if (i == 9) { // 租房付款方式

joural.setPayType(text);

}

else if (i == 10) { // 售價(萬元)

float weishengjian = 0;

try {

weishengjian = Float

.parseFloat(text);

} catch (Exception e) {

weishengjian = 0;

System.out

.println("售價(萬元)的數據格式錯誤異常: "

+ e.getMessage());

}

joural.setSalePrice(weishengjian);

}

else if (i == 11) { // 建築面積(㎡)

float weishengjian = 0;

try {

weishengjian = Float

.parseFloat(text);

} catch (Exception e) {

weishengjian = 0;

System.out

.println("建築面積(㎡)的數據格式錯誤異常: "

+ e.getMessage());

}

joural.setBuiltArea(weishengjian);

}

else if (i == 12) { // 房間數量

int weishengjian = 0;

try {

weishengjian = Integer

.parseInt(text);

} catch (Exception e) {

weishengjian = 0;

System.out

.println("房間數量的數據格式錯誤異常: "

+ e.getMessage());

}

joural.setBedroomCount(weishengjian);

}

else if (i == 13) { // 客廳數量

int weishengjian = 0;

try {

weishengjian = Integer

.parseInt(text);

} catch (Exception e) {

weishengjian = 0;

System.out

.println("客廳數量的數據格式錯誤異常: "

+ e.getMessage());

}

joural.setSittingroomCount(weishengjian);

}

else if (i == 14) { // 衛生間數量

int weishengjian = 0;

try {

weishengjian = Integer

.parseInt(text);

} catch (Exception e) {

weishengjian = 0;

System.out.println("衛生間數量的數據格式錯誤異常: "

+ e.getMessage());

}

joural.setToilet(weishengjian);

}

else if (i == 15) { // 陽臺數量

int yangt = 0;

try {

yangt = Integer.parseInt(text);

} catch (Exception e) {

yangt = 0;

System.out.println(text+" 陽臺數量的數據格式錯誤異常: "

+ e.getMessage());

}

joural.setBalconyCount(yangt);

}

}

cooperationDao.addFteCooperatonJournal(joural);

if (numMap.get(String.valueOf(joural.getAgentUserId()))==null) { //當這個經紀人ID 和活動ID 已經分配短號後,就沒有必要分配

if (cooperationDao.addCooperation4008Num(joural.getAgentUserId(), null, joural.getActivityId())) { //FTE_COOPERATION_4008NUM 添加數據

boolean flag = false;

if (asignNumList.size()>0) {

String num400 = ((Map)asignNumList.get(0)).get("NUM_400TEL_SMALL").toString();

asignNumList.remove(0);

flag = save4008Data(joural.getAgentUserId(),joural.getActivityId(), num400);

}

if (!flag) returnValue = "1";

}

numMap.put(String.valueOf(joural.getAgentUserId()), activityId);

} else if ("0".equals(numMap.get(joural.getAgentUserId()))) { //防止上一次導入數據沒分配4008短號

returnValue = "1";

}

}

 

}

}

} catch (Exception e) {

e.printStackTrace();

}

return returnValue;

}

 

用到的 CooperationExcelUtil 類 =》 excel 處理類

package com.fte.manage.core;

 

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.PushbackInputStream;

import java.text.DecimalFormat;

import java.util.ArrayList;

import java.util.List;

 

import org.apache.poi.POIXMLDocument;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

 

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

import org.apache.poi.openxml4j.opc.OPCPackage;

import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.DateUtil;

import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.ss.usermodel.Workbook;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

 

 

import com.fte.manage.domain.FtePropJournal;

 

public class CooperationExcelUtil {

/** *//** 總行數 */

//    private static int totalRows = 0;

   

    /** *//** 總列數 */

//    private static int totalCells = 0;

   

    /** *//** 構造方法 */

    public CooperationExcelUtil()

    {}

 

    /** *//**

     * <ul>

     * <li>Description:[根據文件名讀取excel文件]</li>

     * <li>Created by [Huyvanpull] [Jan 20, 2010]</li>

     * <li>Midified by [modifier] [modified time]</li>

     * <ul>

     *

     * @param fileName

     * @return

     * @throws Exception

     */

public static List<ArrayList<String>> read(String fileName) {

List<ArrayList<String>> dataLst = new ArrayList<ArrayList<String>>();

 

/** *//** 檢查文件名是否爲空或者是否是Excel格式的文件 */

if (fileName == null || !fileName.matches("^.+\\.(?i)((xls)|(xlsx))$")) {

return dataLst;

}

 

boolean isExcel2003 = true;

/** *//** 對文件的合法性進行驗證 */

if (fileName.matches("^.+\\.(?i)(xlsx)$")) {

isExcel2003 = false;

 

//System.out.println("2007");

}

 

/** *//** 檢查文件是否存在 */

File file = new File(fileName);

if (file == null || !file.exists()) {

return dataLst;

}

 

try {

/** *//** 調用本類提供的根據流讀取的方法 */

dataLst = read(new FileInputStream(file), isExcel2003);

} catch (Exception ex) {

ex.printStackTrace();

}

 

/** *//** 返回最後讀取的結果 */

return dataLst;

}

 

/** *//**

     * <ul>

     * <li>Description:[根據流讀取Excel文件]</li>

     * <li>Created by [Huyvanpull] [Jan 20, 2010]</li>

     * <li>Midified by [modifier] [modified time]</li>

     * <ul>

     *

     * @param inputStream

     * @param isExcel2003

     * @return

     */

public static List<ArrayList<String>> read(InputStream inputStream,

boolean isExcel2003) {

List<ArrayList<String>> dataLst = null;

try {

 /** *//** 根據版本選擇創建Workbook的方式 */

// Workbook wb = isExcel2003 ? new HSSFWorkbook(inputStream): new XSSFWorkbook(inputStream);

Workbook wb =create(inputStream);

dataLst = read(wb);

} catch (Exception e) {

e.printStackTrace();

}

return dataLst;

}

 

/** *//**

     * <ul>

     * <li>Description:[得到總行數]</li>

     * <li>Created by [Huyvanpull] [Jan 20, 2010]</li>

     * <li>Midified by [modifier] [modified time]</li>

     * <ul>

     *

     * @return

     */

// public int getTotalRows() {

// return totalRows;

// }

 

/** *//**

     * <ul>

     * <li>Description:[得到總列數]</li>

     * <li>Created by [Huyvanpull] [Jan 20, 2010]</li>

     * <li>Midified by [modifier] [modified time]</li>

     * <ul>

     *

     * @return

     */

// public int getTotalCells() {

// return totalCells;

// }

 

/** *//**

     * <ul>

     * <li>Description:[讀取數據]</li>

     * <li>Created by [Huyvanpull] [Jan 20, 2010]</li>

     * <li>Midified by [modifier] [modified time]</li>

     * <ul>

     *

     * @param wb

     * @return

     */

private static List<ArrayList<String>> read(Workbook wb) {

List<ArrayList<String>> dataLst = new ArrayList<ArrayList<String>>();

int totalCells=0;

/** *//** 得到第一個shell */

Sheet sheet = wb.getSheetAt(0);

int totalRows = sheet.getPhysicalNumberOfRows();

if (totalRows >= 1 && sheet.getRow(0) != null) {

totalCells = sheet.getRow(0).getPhysicalNumberOfCells();

}

 

/** *//** 循環Excel的行 */

for (int r = 1; r < totalRows; r++) {

Row row = sheet.getRow(r);

if (row == null) {

continue;

}

 

ArrayList<String> rowLst = new ArrayList<String>();

/** *//** 循環Excel的列 */

for (short c = 0; c < totalCells; c++) {

Cell cell = row.getCell(c);

String cellValue = "";

if (cell == null) {

rowLst.add(cellValue);

continue;

}

 

/** *//** 處理數字型的,自動去零 */

if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) {

/** *//** 在excel裏,日期也是數字,在此要進行判斷 */

 

if (HSSFDateUtil.isCellDateFormatted(cell)) {

cellValue = DateUtil.getExcelDate(cell

.getDateCellValue(), true)

+ "";

} else {

cellValue = getRightStr(cell.getNumericCellValue() + "");

}

}

/** *//** 處理字符串型 */

                else if (Cell.CELL_TYPE_STRING == cell.getCellType())

                {

                    cellValue = cell.getStringCellValue();

                }

                /** *//** 處理布爾型 */

                else if (Cell.CELL_TYPE_BOOLEAN == cell.getCellType())

                {

                    cellValue = cell.getBooleanCellValue() + "";

                }

                /** *//** 其它的,非以上幾種數據類型 */

else {

cellValue = cell.toString() + "";

}

 

rowLst.add(cellValue);

}

dataLst.add(rowLst);

}

return dataLst;

}

public static Workbook create(InputStream inp) throws IOException,InvalidFormatException {

   if (!inp.markSupported()) {

       inp = new PushbackInputStream(inp, 8);

   }

   if (POIFSFileSystem.hasPOIFSHeader(inp)) {

       return new HSSFWorkbook(inp);

   }

   if (POIXMLDocument.hasOOXMLHeader(inp)) {

       return new XSSFWorkbook(OPCPackage.open(inp));

   }

   throw new IllegalArgumentException("你的excel版本目前poi解析不了");

}

 

/** *//**

     * <ul>

     * <li>Description:[正確地處理整數後自動加零的情況]</li>

     * <li>Created by [Huyvanpull] [Jan 20, 2010]</li>

     * <li>Midified by [modifier] [modified time]</li>

     * <ul>

     *

     * @param sNum

     * @return

     */

public static String getRightStr(String sNum) {

DecimalFormat decimalFormat = new DecimalFormat("#.000000");

String resultStr = decimalFormat.format(new Double(sNum));

if (resultStr.matches("^[-+]?\\d+\\.[0]+$")) {

resultStr = resultStr.substring(0, resultStr.indexOf("."));

}

return resultStr;

}

 

/** *//**

     * <ul>

     * <li>Description:[測試main方法]</li>

     * <li>Created by [Huyvanpull] [Jan 20, 2010]</li>

     * <li>Midified by [modifier] [modified time]</li>

     * <ul>

     *

     * @param args

     * @throws Exception

     */

public static void main(String[] args) throws Exception {

List<ArrayList<String>> dataLst = new CooperationExcelUtil()

.read("D:\\data\\homes\\ftesitemanage\\temp\\1342776532205.xls");

System.out.println(dataLst);

/*

for (ArrayList<String> innerLst : dataLst) {

String rowData = dataLst.size()+"";

for (String dataStr : innerLst) {

System.out.println(dataStr);

}

for(int i=0;i<innerLst.size();i++){

if(i==0){

System.out.println( "i=0 :"+  innerLst.get(i));

}

if(i==1){

System.out.println( "i=1 :"+  innerLst.get(i));

}

if(i==2){

System.out.println( "i=2 :"+  innerLst.get(i));

}

System.out.println("--------------");

}

for (String dataStr : innerLst) {

System.out.print(dataStr+"\t");

rowData.append(",").append(dataStr);

System.out.println(rowData);

if (dataStr.equals("")) {

rowData.append("null");

}

 

}

}

*/

}

}

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章