Spring+SpringMVC+Maven+MyBatis+Mysql此环境下的POI导入
此文档讲解Excel导入的功能
1.1 POI导入excel
浏览器效果展示:
前端代码
前端Html代码:
<!-- 导入 -->
<div class="layui-inline">
<div class="layui-input-block" style="margin-left: 10px;">
<button type="button" permission="49" class="layui-btn layui-btn-small">
<input type="file" name="picture" id="picture">
</button>
</div>
</div>
<div class="layui-inline">
<div class="layui-input-block" style="margin-left: 10px;">
<button type="button" permission="49" id="scheduExcel" class="layui-btn layui-btn-small">Excel导入</button>
</div>
</div>
<!-- 导出 -->
<div class="layui-inline">
<div class="layui-input-block" style="margin-left: 10px;">
<button type="button" permission="49" id="exportExcel" class="layui-btn layui-btn-small">Excel导出</button>
</div>
</div>
Js代码
//JS校验form表单信息
<script>
function checkData() {
var fileDir = $("#picture").val();
var suffix = fileDir.substr(fileDir.lastIndexOf("."));
if("" == fileDir) {
alert("选择需要导入的Excel文件!");
return false;
}
if(".xls" != suffix && ".xlsx" != suffix) {
alert("选择Excel格式的文件导入!");
return false;
}
return true;
}
//Excel表格导入
var importExcelhospDeptDoc = function() {
if(!checkData()) {
return;
}
//表单传值
var form = new FormData(document.getElementById("excelScheduForm"));
$.ajax({
type: "post",
dataType: "json",
processData: false, //表单传值必须
contentType: false, //表单传值必须
url: "/importExcel/importShopingOrder",
data: form,
success: function(msg) {
//debugger;
if(msg.resultCode == 200) {
alert(msg.msg);
window.location.reload();
} else if(msg.resultCode == 400) {
alert(msg.msg);
document.getElementById("errorSoCode").innerText=msg.content;
document.getElementById("picture").value="";
}
}
});
}
//导入商城订单
$('#scheduExcel').on('click', function() {
importExcelhospDeptDoc();
});
</script>
依赖包注入(pom.xml)
<!-- poi Excel导入导出 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- 上传文件 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
Controller控制层
@ResponseBody
@RequestMapping(value = "/importShopingOrder", method = { RequestMethod.GET, RequestMethod.POST })
public Result uploadShopingOrder(HttpServletRequest request, MultipartFile picture, HttpSession session,HttpServletResponse response)
throws Exception {
Logger.info("临时表格数据导入:picture:" + picture);
Result result = new Result();
StringBuffer errorSoCode= new StringBuffer("出错订单号为:");
if (picture != null && picture.getOriginalFilename() != null && picture.getOriginalFilename().length() > 0) {
InputStream in = null;
List<List<Object>> listob = null;
in = picture.getInputStream();
listob = new ImportExcelUtil().getBankListByExcel(in, picture.getOriginalFilename(),1);
in.close();
UserBk user = (UserBk)session.getAttribute("users");
int flag = 0;
// 该处可调用service相应方法进行数据保存到数据库中,现只对数据输出
if(listob == null) {
result.setMsg("格式不符合要求");
result.setResultCode(400);
return result;
}
for (int i = 0; i < listob.size(); i++) {
List<Object> lo = listob.get(i);
ShoppingOrder shoppingOrder = new ShoppingOrder();
shoppingOrder.setSoCode(String.valueOf(lo.get(3)));
shoppingOrder.setSender("兑换码");
shoppingOrder.setSenderCode(String.valueOf(lo.get(10)));
//list.add(shoppingOrder);
shoppingOrder.setOperator(user.getuName());
int updateStatus = shoppingOrderService.updateShoppingOrderRecord(shoppingOrder);
if(updateStatus > 0 ){
//导入成功 推送已发货消息
scoreHistoryService.goodsDeliver(shoppingOrder.getSoCode(),3);
}else{
errorSoCode.append(lo.get(3)).append(",");
flag=2;
}
}
if(flag == 2) {
result.setContent(errorSoCode);
result.setMsg("部分订单发货失败,请查看页面中红色订单编号!");
result.setResultCode(400);
}else {
result.setMsg("导入成功");
result.setResultCode(200);
}
} else {
result.setMsg("表格不存在");
result.setResultCode(400);
}
return result;
}
ImportExcelUtil
package cn.medbridge.ss.utils;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.plaf.basic.BasicComboBoxUI.ListDataHandler;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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;
/**
* Description:Excel表格导入工具类
*/
public class ImportExcelUtil {
/**
* 日志监控
*/
// private static Logger Logger =
// LogManager.getLogger(ImportExcelUtil.class);
private final static String excel2003L = ".xls"; // 2003-版本的Excel
private final static String excel2007U = ".xlsx"; // 2007+版本的Excel
/**
* @Description:获取IO流中的数据,组装成List<List<Object>>对象
*
* @auther:liang.ma
* @param in
* @param fileName
* @return
* @throws Exception
* @time:2017年9月13日下午4:38:07
*/
public List<List<Object>> getBankListByExcel(InputStream in, String fileName,int type) throws Exception {
List<List<Object>> list = null;
// 创建Excel工作薄
Workbook work = this.getWorkbook(in, fileName);
if (null == work) {
throw new Exception("创建Excel工作薄为空!");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
list = new ArrayList<List<Object>>();
// 遍历Excel中所有的sheet
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if (sheet == null) {
continue;
}
// 遍历当前sheet中的所有行
for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
row = sheet.getRow(j);
if (row == null || row.getFirstCellNum() == j) {
continue;
}
// 遍历所有的列
List<Object> li = new ArrayList<Object>();
for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
if(type == 1) {
if (cell != null && cell .getCellType() != Cell.CELL_TYPE_BLANK) {
li.add(this.getCellValue(cell));
}else {
list = null;
return list;
}
}else {
if (cell != null && cell .getCellType() != Cell.CELL_TYPE_BLANK) {
li.add(this.getCellValue(cell));
}
}
}
if (li != null && li.size() >0) {
list.add(li);
}
}
}
// work.close();
return list;
}
/**
* @Description:根据文件后缀,自适应上传文件的版本
* @auther:liang.ma
* @param inStr
* @param fileName
* @return
* @throws Exception
* @time:2017年9月13日下午4:38:21
*/
public Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
Workbook wb = null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if (excel2003L.equals(fileType)) {
wb = new HSSFWorkbook(inStr); // 2003-
} else if (excel2007U.equals(fileType)) {
wb = new XSSFWorkbook(inStr); // 2007+
} else {
throw new Exception("解析的文件格式有误!");
}
return wb;
}
/**
* @Description:对表格中数值进行格式化
* @auther:liang.ma
* @param cell
* @return
* @time:2017年9月13日下午4:38:33
*/
public Object getCellValue(Cell cell) {
Object value = null;
DecimalFormat df = new DecimalFormat("0"); // 格式化number String字符
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); // 日期格式化
DecimalFormat df2 = new DecimalFormat("0.00"); // 格式化数字
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
value = cell.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC:
if ("General".equals(cell.getCellStyle().getDataFormatString())) {
value = df.format(cell.getNumericCellValue());
} else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
value = sdf.format(cell.getDateCellValue());
} else {
value = df2.format(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
value = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_BLANK:
value = "";
break;
default:
break;
}
return value;
} else {
return "";
}
}
}
Service业务逻辑层
Service层:
/**
* 商城订单导入更新记录 单条更新
* @param shoppingOrder
* @return
*/
int updateShoppingOrderRecord(ShoppingOrder shoppingOrder);
service实现类
/**
* 商城订单导入单条更新记录
*/
@Override
public int updateShoppingOrderRecord(ShoppingOrder shoppingOrder) {
return shoppingOrderMapper.updateShoppingOrderRecord(shoppingOrder);
}
Mapper持久层
//商城订单导入更新记录 单条
int updateShoppingOrderRecord(ShoppingOrder shoppingOrder);
XML配置层
<!-- 单条更新商城订单 -->
<update id="updateShoppingOrderRecord" parameterType="cn.medbridge.ss.model.ShoppingOrder">
UPDATE ss_shopping_order sso
set sso.sender = #{sender,jdbcType=VARCHAR},
sso.sender_code = #{senderCode,jdbcType=VARCHAR},
sso.operator = #{operator,jdbcType=VARCHAR},
sso.so_status = 3
WHERE sso.so_code = #{soCode,jdbcType=VARCHAR}
AND sso.so_status = 4
</update>