直接上代碼了
前端使用layui框架和js
<div class="layui-form-item parent-menu">
<label class="layui-form-label" style="width: 120px;">選擇數據包文件</label>
<div class="layui-input-block" style="margin-left: 180px;">
<div class="layui-upload">
<button type="button" class="layui-btn layui-btn-normal" id="seleceFile">選擇Excel文件</button>
</div>
</div>
</div>
向後臺發出請求
//文件上傳
upload.render({
elem:'#seleceFile'
,url:'/goods/importTable'//上傳接口
,accept:'file'
,acceptMime:""
,auto:false
,multiple:true
,bindAction:'#importBtn'
,data:{
categoryTypeId:function(){
return $("#categoryType_id").val();
}
}
,done:function(res){
//上傳完畢回調
if(res.code==0){
layer.msg(res.msg);
parent.layer.close(index);
}else{
layer.msg(res.msg);
}
}
,error:function () {
//請求異常回調
}
})
我這邊主要是上傳一個商品的Excel,根據Excel表格格式,取出對應行列中的數據,封成商品對象集合並存儲到數據庫中
@RequestMapping("importTable")
@ResponseBody
public ResultObj importTable(@RequestParam("file")MultipartFile
file,HttpServletRequest request, HttpServletResponse response) {
User user = (User) WebUtils.getSession().getAttribute("user");
Goods goodslist=null;
List<Goods> list=new ArrayList<Goods>();
ReadExcel readExcel= new ReadExcel();
//取出Excel表格中數據並封裝成對象返回
List<Goods> goodsList = readExcel.getGoodsExcelInfo(file);
try {
for(Goods goods : goodsList) {
goodslist = new Goods();
if(goods.getGoodsName()!=null) {goodslist.setGoodsName(goods.getGoodsName());}
if(goods.getGoodsSamllImgUrl()!=null) {goodslist.setGoodsSamllImgUrl(goods.getGoodsSamllImgUrl());}
if(goods.getStock()!=null) {goodslist.setStock(goods.getStock());}
if(goods.getAddPrice()!=null) {goodslist.setAddPrice(goods.getAddPrice());}
if(goods.getMarkerPrice()!=null) { goodslist.setMarkerPrice(goods.getMarkerPrice());}
list.add(goodslist);
}
goodsService.saveBatch(list);
return ResultObj.UPLOAD_SUCCESS;
} catch (Exception e) {
e.printStackTrace();
return ResultObj.UPLOAD_ERROR;
}
}
下面是具體取出Excel表格數據並封裝對象集合返回
/*
* 商品文件上傳
* */
public List<Goods> getGoodsExcelInfo(MultipartFile mFile) {
String fileName = mFile.getOriginalFilename();// 獲取文件名
List<Goods> goodsList = null;
try {
if (!validateExcel(fileName)) {// 驗證文件名是否合格
return null;
}
boolean isExcel2003 = true;// 根據文件名判斷文件是2003版本還是2007版本
if (isExcel2007(fileName)) {
isExcel2003 = false;
}
goodsList = createGoodsExcel(mFile.getInputStream(), isExcel2003);
} catch (Exception e) {
e.printStackTrace();
}
return goodsList;
}
/*
* 讀取表中商品信息
* */
public List<Goods> createGoodsExcel(InputStream is, boolean isExcel2003) {
List<Goods> goodsList = null;
try {
Workbook wb = null;
if (isExcel2003) {// 當excel是2003時,創建excel2003
wb = new HSSFWorkbook(is);
} else {// 當excel是2007時,創建excel2007
wb = new XSSFWorkbook(is);
}
goodsList = readGoodsExcelValue(wb);// 讀取Excel裏面的信息
} catch (IOException e) {
e.printStackTrace();
}
return goodsList;
}
/*
* 讀取信息
* */
private List<Goods> readGoodsExcelValue(Workbook wb) {
// 得到第一個shell
Sheet sheet = wb.getSheetAt(0);
// 得到Excel的行數
this.totalRows = sheet.getPhysicalNumberOfRows();
// 得到Excel的列數(前提是有行數)
if (totalRows > 1 && sheet.getRow(0) != null) {
this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
List<Goods> goodsList = new ArrayList<Goods>();
// 循環Excel行數,我直接從我有數據的那一行開始遍歷
for (int r = 3; r < totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
Goods goods = new Goods();
// 循環Excel的列
for (int c = 0; c < this.totalCells; c++) {
Cell cell = row.getCell(c);
if (null != cell) {
//取出列中數據並返回給對象,我只取出我需要列中的數據
if (c == 1) {
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
String goodsName = String.valueOf(cell.getNumericCellValue());
goods.setGoodsName(goodsName.substring(0, goodsName.length() - 2 > 0 ? goodsName.length() - 2 : 1));// 名稱
}else{
goods.setGoodsName(cell.getStringCellValue());//名稱
}
} else if (c == 3) {
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
String goodsSamllImgUrl = String.valueOf(cell.getNumericCellValue());
goods.setGoodsSamllImgUrl(goodsSamllImgUrl.substring(0, goodsSamllImgUrl.length() - 2 > 0 ? goodsSamllImgUrl.length() - 2 : 1));
}else {
goods.setGoodsSamllImgUrl(cell.getStringCellValue());//圖片
}
}else if (c == 12) {
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
String stock = String.valueOf(cell.getNumericCellValue());
goods.setStock(Integer.parseInt(stock.substring(0, stock.length() - 2 > 0 ? stock.length() - 2 : 1)));
}else {
goods.setStock(20);// 庫存
}
}else if (c == 15) {
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
String markerPrice = String.valueOf(cell.getNumericCellValue());
BigDecimal b = new BigDecimal(markerPrice);
goods.setMarkerPrice(b);
}else {
goods.setMarkerPrice(BigDecimal.valueOf(cell.getNumericCellValue()));// 市場價
}
}
}
}
// 添加到list
goodsList.add(goods);
}
return goodsList;
}
/**
* 驗證EXCEL文件
* @param filePath
* @return
*/
public boolean validateExcel(String filePath) {
if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
errorMsg = "文件名不是excel格式";
return false;
}
return true;
}
// @描述:是否是2003的excel,返回true是2003
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}
// @描述:是否是2007的excel,返回true是2007
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}