您的位置:首页 > 编程语言 > Java开发

springMVC导入excel案例poi

2016-02-03 15:28 435 查看
直接上代码:

第一步,controller 引入

private static final String CHECK_FILE = "checkExceFile";
/**
* 对账文件导入
*
* file 对账excel文件
* providerCode 编号参数
* type 支付类型
*
*/
@RequestMapping("preview")
@ResponseBody
public JsonResult preview(@RequestParam("checkFile") MultipartFile file, String providerCode, String type, HttpSession session) {
try {

MandoAssert.notNull(type, "对账类型错误");

MandoAssert.notNull(providerCode, "对账方式未选择");

List<CheckAccount> accountorders = CheckAccountUtil.checkAccount(file, providerCode, type);

JsonResult result = JsonResult.buildSuccessResult(accountorders);

session.setAttribute(CHECK_FILE, accountorders);
return result.setModel("file", session.getId());
} catch (Exception e) {
String mgs = "对账文件解析失败";

return ResponseExceptionMessage.getResponseExceptionMessage(logger, mgs, e);
}
}
/**
* 构建成功的交互对象, 不分页
*
* @param items 列表数据
* @return JSON封装对象
*/
public static <E> CollectionJsonResult buildSuccessResult(final List<E> items) {

List<E> tmpdata = items;

if (items == null) {
tmpdata = new LinkedList<E>();
}

CollectionJsonResult result = new CollectionJsonResult();
result.setSuccess(true);
result.setItems(tmpdata);

return result;
}


第二步:CheckAccountUtil 解析传入的excel .

package com.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
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.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.zhonglian.pub.support.enums.CheckAccountType;
import com.support.exception.Exception; import com.support.utils.OptionalUtils;
import com.mybatis.entity.CheckAccount;

/**
*
* @author chenyq
* @Description: 对账工具类
* @date 2016年1月13日
*/
public class CheckAccountUtil {

private static final Logger log = LoggerFactory.getLogger(CheckAccountUtil.class);

/** 时间格式数组(年月日 时分秒) */
48    
public static final String DATE_FULL_STR = "yyyy-MM-dd HH:mm:ss";

private static final String OFFICE_EXCEL_XLS = ".xls";

private static final String OFFICE_EXCEL_XLSX = ".xlsx";

static final String NUMBER_REG = "^\\d*(\\.\\d*|)$";

/**
* spring mvc 文件外部处理接口
*
* @param file 上传文件
* @param symbol 对账机构编号集合
* @param type 对账类型
*
* @return List<CheckAccount> 解析完成的对账信息
*/
public static List<CheckAccount> checkAccount(MultipartFile file, String code, CheckAccountType type) {
if (file == null || file.isEmpty())
throw new Exception("file is null");

if (file.getOriginalFilename().endsWith(OFFICE_EXCEL_XLS))
return readXLS(file, code, type);
else if (file.getOriginalFilename().endsWith(OFFICE_EXCEL_XLSX))
return readXLSX(file, code, type);
else
throw new Exception("file does not support:" + file.getOriginalFilename());
}

/**
* 普通文件外部处理接口
*
* @param file 对账文件
* @param type 对账类型
*
* @return List<CheckAccount> 解析完成的对账信息
*/
public static List<CheckAccount> accountOrders(File file, String code, CheckAccountType type) {
if (file == null || !file.exists())
throw new IllegalArgumentException("file is null");

if (file.getName().endsWith(OFFICE_EXCEL_XLS)){
log.info("---------------xls----------");
return readXLS(file,code, type);
} else if (file.getName().endsWith(OFFICE_EXCEL_XLSX))
return readXLSX(file,code, type);
else
throw new IllegalArgumentException("file does not support:" + file.getName());
}

/**
*
* 最终处理方法
*
* @param file 文件流
* @param symbol 对账机构编号集合
* @param type 对账类型
*
* @return List<CheckAccount> 解析完成的对账信息
*/
private static List<CheckAccount> readXLS(InputStream input, String code, CheckAccountType type) {
try {
POIFSFileSystem fs = new POIFSFileSystem(input);
HSSFWorkbook wb = new HSSFWorkbook(fs, true);

return resolve(wb, code, type);
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new Exception("文件解析错误");
}
}

/**
*
* 普通文件处理方法
*
* @param file 对账文件
* @param symbol 对账机构编号集合
* @param type 对账类型
*
* @return List<CheckAccount> 解析完成的对账信息
*/
private static List<CheckAccount> readXLS(File file, String code, CheckAccountType type) {
try (InputStream input = new FileInputStream(file)) {
return readXLS(input,code, type);
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new Exception("文件提取错误");
}
}

/**
*
* spring mvc 文件处理方法
*
* @param file 上传文件
* @param symbol 对账机构编号集合
* @param type 对账类型
*
* @return List<CheckAccount> 解析完成的对账信息
*/
private static List<CheckAccount> readXLS(MultipartFile file, String code, CheckAccountType type) {
try (InputStream input = file.getInputStream()) {
return readXLS(input,code,type);
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new Exception("文件提取错误");
}
}

/**
*
* 最终处理方法
*
* @param file 文件流
* @param symbol 对账机构编号集合
* @param type 对账类型
*
* @return List<CheckAccount> 解析完成的对账信息
*/
private static List<CheckAccount> readXLSX(InputStream input, String code, CheckAccountType type) {
try {
OPCPackage op = OPCPackage.open(input);
XSSFWorkbook wb = new XSSFWorkbook(op);

return resolve(wb, code, type);
} catch (InvalidFormatException | IOException e) {
log.error(e.getMessage(), e);
throw new Exception("文件解析错误");
}
}

/**
*
* 普通文件处理方法
*
*
*/
private static List<CheckAccount> readXLSX(File file,  String code, CheckAccountType type) {
List<CheckAccount> list = new ArrayList<>();

try (InputStream input = new FileInputStream(file)) {
list = readXLSX(input, code, type);
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new Exception("文件提取错误");
}
return list;
}

/**
*
* spring mvc 文件处理方法
*
*
*/
private static List<CheckAccount> readXLSX(MultipartFile file, String code, CheckAccountType type) {
try (InputStream input = file.getInputStream()) {
return readXLSX(input,code, type);
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new Exception("文件提取错误");
}
}

private static List<CheckAccount> resolve(Workbook wb, String code, CheckAccountType type) {
int sheets = wb.getNumberOfSheets();

List<CheckAccount> list = new ArrayList<>();

CheckAccount accountOrder;

int curSheets;
int curRows;
Sheet sheet;

for (int i = 0; i < sheets; i++) {
curSheets = i;
sheet = wb.getSheetAt(i);

if (sheet == null)
continue;

for (Row row : sheet) {

if (OptionalUtils.isPersent(row)) {

curRows = row.getRowNum();
Cell zero = row.getCell(0);

if ((curSheets == 0 && curRows == 0))
continue;
else if (OptionalUtils.notPersent(zero))
break;
accountOrder = new CheckAccount();
accountOrder.setProviderCode(code);

for (Cell cell : row) {

if (OptionalUtils.isPersent(cell))
cell(cell, accountOrder, curSheets, curRows, code, type);
else
continue;

}
list.add(accountOrder);

} else {
continue;
}

}
}

return list;
}

private static void cell(Cell cell, CheckAccount accountOrder, int curSheets, int curRows, String code, CheckAccountType type) {
int curCal = cell.getColumnIndex();

try {
String str = getCellValue(cell);
checkAccountSetValue(curCal, str, accountOrder);
//            log.info("类型不支持进行解析,type:"+type);
} catch (Exception e) {
log.error(e.getMessage(), e);
if (e instanceof IllegalArgumentException || e instanceof Exception)
throw new Exception(
"消息错误:" + e.getMessage() + ";" + (curSheets + 1) + "页," + (curRows + 1) + "行," + (curCal + 1) + "列");
else
throw new Exception("消息错误:" + (curSheets + 1) + "页," + (curRows + 1) + "行," + (curCal + 1) + "列");

}
}

static String getCellValue(Cell cell) {
Object obj = "";
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
obj = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
obj = cell.getNumericCellValue();
break;
case Cell.CELL_TYPE_FORMULA:
obj = cell.getCellFormula();
break;
case Cell.CELL_TYPE_ERROR:
obj = cell.getErrorCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN:
obj = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_BLANK:
break;
}

return String.valueOf(obj).trim();
}
//解析excel例子
private static void checkAccountSetValue(int index, String str, CheckAccount accountOrder) {
switch (index) {
case 0: //流水号  // 第一个值
MandoAssert.isTrue(StringUtils.isNotEmpty(str), "对账流水号不能为空");
accountOrder.setTradeCode(str);
break;
//        case 1: //银通订单号(略)
//            break;
case 2: //创建时间
MandoAssert.isTrue(StringUtils.isNotEmpty(str), "订单时间不能为空");
accountOrder.setTradeDate(getDateValue(str));
break;
//        case 3: //成功时间(略)
//            break;
case 4://交易金额(元)
MandoAssert.isTrue(str.matches(NUMBER_REG), "对账金额数据错误 :" + str);
accountOrder.setAmount(new BigDecimal(str));
break;
//        case 5://退款金额(略)
//            break;
case 6: // 交易状态
MandoAssert.isTrue(StringUtils.isNotEmpty(str), "交易状态不能为空");
accountOrder.setState(str);
break;
case 7: //商品名称
MandoAssert.isTrue(StringUtils.isNotEmpty(str), "商品名称不能为空");
accountOrder.setDescription(str);
break;

}
}

/**
*
* 获取int 值, 有小数的取小数之前的数字
*
* @param str 需要转换的字符串
* @param mage 错误提示信息
*
* @return int
*/
private static int getIntValue(String str, String mage) {
MandoAssert.isTrue(str.matches(NUMBER_REG), mage + str);

if (str.contains(".")) {
str = str.substring(0, str.indexOf("."));
}

return Integer.valueOf(str);
}

/**
*
* 字符串转时间
*
* @param str 需要转换的字符串
*
* @return Date
*/
private static Date getDateValue(String str) {
try { //DATE_FORMAT_FULL ="yyyy-MM-dd HH:mm:ss";
return DateUtils.parseDateStrictly(str, DATE_FORMAT_FULL);
} catch (ParseException e) {
log.error("时间格式不支持:" + str, e);
throw new Exception("时间格式不支持 :" + str + ",支持格式: " + Arrays.asList(DATE_FORMAT_FULL));
}
}

}


第三步:第一步会传回一个file, 这里传入

/**
* 对账文件开始对账
* @param file 第一步会传回一个file 是一个sessionId
* @param params 参数
* @return
*/
@RequestMapping("freshCheck")
@ResponseBody
public JsonResult freshCheck(PaymentParamsVo params, String file, HttpSession session) {

try {

List<CheckAccount> accountorders = (List<CheckAccount>) session.getAttribute(CHECK_FILE); //获取本地session
//            CheckAccountType checkType = (CheckAccountType) session.getAttribute(CHECK_TYPE);

Assert.isTrue(StringUtils.isNotEmpty(file) && file.equals(session.getId()) && OptionalUtils.isPersent(accountorders), "对账文件未导入"); //对比文件

CheckAccount account = checkAccountService.checkAccount(accountorders, params);// 页码、查询到的信息 //去处理的业务

session.removeAttribute(CHECK_FILE);

return JsonResult.buildSuccessResult(accountLog);

} catch (Exception e) {

logger.error(e.getMessage(), e);

return JsonResult.buildFailedResult("对账失败");
}
}


poi处理,要jar的可以去下载也可以留言传送过去poi-3.12.jar,poi-ooxml-3.12.jar,poi-ooxml-schemas-3.12.jar

下载地址 http://i.cnblogs.com/Files.aspx (poi.zip包)

第一步跟第三步分开处理,第一步处理解析excel,返回一个sessionId, 把sessionId传到第三步去处理业务逻辑

对于不太深入的学习者,也可以第一步跟第三步不分开,一起处理,会容易理解写

偶遇晨光原创

2016-02-03
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: