第一步: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");
}
}
}
*/
}
}