您的位置:首页 > 数据库

java实现上传excel,并提取信息然后插入数据库(实际项目代码)

2017-12-12 19:42 615 查看
public Object uploadExcel(MultipartFile uploadfile, String storeNo) throws AnmavException {
JSONObject result = new JSONObject();
String directory = null;
try {
if (StringUtil.isEmpty(uploadfile)) {
logger.error("未检测到文件为空");
return new ResponseBean(AnmavResponseConstant.STATUS_PARAM_ERROR, "未检测到文件不能为空");
}
float size = uploadfile.getSize() / (float) 1024 / (float) 1024;
if (size > 100) {
logger.error("文件大小不能超过100M");
return new ResponseBean(AnmavResponseConstant.STATUS_PARAM_ERROR, "文件大小不能超过100M");
}
String originalName = uploadfile.getOriginalFilename();
if (StringUtil.isEmpty(originalName)) {
logger.error("文件的原始名字为空");
return new ResponseBean(AnmavResponseConstant.STATUS_PARAM_ERROR, "文件的原始名字为空");
}
logger.info("文件名:" + originalName);

if (!originalName.toLowerCase().endsWith(".zip")) {
logger.error("文件格式只能是zip");
return new ResponseBean(AnmavResponseConstant.STATUS_PARAM_ERROR, "文件格式只能是zip");
}

String fileName = FileUtils.getNewName(originalName);
directory = FileUtils.getFolder(config.getExcelDirectory(), storeNo);

String filePath = Paths.get(directory, fileName).toString();
File file = new File(filePath);
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file));
stream.write(uploadfile.getBytes());
stream.close();

// 解压文件 获取里面的excel 文件
ZipUtils.deCompress(file, directory);

List<File> excelList = FileUtils.listFiles(directory, new String[]{
"xls", "xlsx"});
if (StringUtil.isEmpty(excelList) || excelList.size() != 1) {
logger.error("文件格式只能是zip");
FileUtils.deleteDir(new File(directory));
return new ResponseBean(AnmavResponseConstant.STATUS_PARAM_ERROR, "压缩包中应只能包含一个Excel文件");
}

// 获取模板文件 进行解析
File excelFile = excelList.get(0);

// 获取菜品类别 单位设置 工作间设置

// 获取菜品类别
MenuBarBean barParam = new MenuBarBean();
barParam.setStoreNo(storeNo);
List<MenuBarBean> barList = menuBarDao.selectByStoreNo(barParam);

// 获取单位信息
UnitInfoBean unitParam = new UnitInfoBean();
unitParam.setStoreNo(storeNo);
List<UnitInfoBean> unitList = unitInfoDao.selectSomeUnitInfo(unitParam);

// 获取工作间信息
WorkshopInfoBean workParam = new WorkshopInfoBean();
workParam.setStoreNo(storeNo);
List<WorkshopInfoBean> workList = workshopInfoDao.selectWorkshopMenu(workParam);

// 上传成功
JSONObject respData = batchAddMenu(excelFile,
directory, barList, unitList, workList, storeNo);

String code = respData.getString("respCode");
String data = respData.getString("respData");
result.put("respData", data);
if (!"00".equals(code)) {
throw new Exception(respData.getString("message"));
}
result.put("respCode", "00");
result.put("message", "操作成功");
FileUtils.deleteDir(new File(directory));
return new ResponseBean(result);
} catch (Exception e) {
result.put("respCode", "01");
result.put("message", e.getMessage());
logger.info("修改出错:" + e.getMessage());
FileUtils.deleteDir(new File(directory));
return new ResponseBean(result);
}
}

public JSONObject batchAddMenu(File excelFile, String filePath, List<MenuBarBean> barList, List<UnitInfoBean> unitList, List<WorkshopInfoBean> workList, String storeNo) {
JSONObject result = new JSONObject();
try {

//File file = new File(filePath);
Workbook workbook = Workbook.getWorkbook(excelFile);
Sheet sheet = workbook.getSheet(0);
//获取行数 和列数
//行数
int maxRow = sheet.getRows();
int maxColumn = sheet.getColumns();
if (maxRow <= 1) {
logger.error("Excel文件中无菜单数据数据,行数不能小于1");
throw new Exception("Excel文件中无菜单数据数据,行数不能小于1");
}

if (maxRow >= 1000) {
logger.error("Excel中每次最多为1000条数据");
throw new Exception("Excel中每次最多为1000条数据");
}

if (maxColumn != 12) {
logger.error("必须是12列数据");
throw new Exception("必须是12列数据");
}

//处理List数据
List<String> barNameList = new ArrayList<>();
Map<String, String> menuBarMap = new HashMap<>();
for (MenuBarBean menuBar : barList) {
if (!StringUtil.isEmpty(menuBar)) {
barNameList.add(menuBar.getMenuBarName());
menuBarMap.put(menuBar.getMenuBarName(), menuBar.getMenuBarNo());
}
}

List<String> unitNameList = new ArrayList<>();
Map<String, Integer> unitMap = new HashMap<>();
for (UnitInfoBean unitInfo : unitList) {
if (!StringUtil.isEmpty(unitInfo)) {
unitNameList.add(unitInfo.getUnitName());
unitMap.put(unitInfo.getUnitName(), unitInfo.getId());
}
}

List<String> workNameList = new ArrayList<>();
Map<String, Integer> workMap = new HashMap<>();
for (WorkshopInfoBean workInfo : workList) {
if (StringUtil.isEmpty(workInfo)) {
workNameList.add(workInfo.getWorkshopName());
workMap.put(workInfo.getWorkshopName(), workInfo.getId());
}
}

//获取所有的菜单名称
MenuDetailsBean menuDetailsParam = new MenuDetailsBean();
menuDetailsParam.setStoreNo(storeNo);
List<MenuDetailsBean> menuList = menuDetailsDao.selectByStoreNo(menuDetailsParam);

Map<String, Integer> tjdMap = new HashMap<>();
tjdMap.put("一星", 1);
tjdMap.put("一星半", 2);
tjdMap.put("二星", 3);
tjdMap.put("二星半", 4);
tjdMap.put("三星", 5);
tjdMap.put("三星半", 6);
tjdMap.put("四星", 7);
tjdMap.put("四星半", 8);
tjdMap.put("五星", 9);
List<String> menuNameList = new ArrayList<String>();
//List<String> menuShortNameList = new ArrayList<String>();
List<String> menuSerList = new ArrayList<String>();

for (MenuDetailsBean detail2 : menuList) {
if (!StringUtil.isEmpty(detail2)) {
menuNameList.add(detail2.getMenuName());
//menuShortNameList.add(e)
menuSerList.add(detail2.getMenuNo());
}
}

List<MenuDetailsBean> menus = new ArrayList<MenuDetailsBean>();

MenuUploadInfo uploadInfo = new MenuUploadInfo();
uploadInfo.setStoreNo(storeNo);
uploadInfo.setAddTime(DateUtils.getCurrentDateString());
uploadInfo.setAddUser("");
uploadInfo.setFilePath(filePath);
uploadInfo.setFileSize(excelFile.length() + "B");

//首先插入上传的记录 在插入详情记录

List<MenuUploadDetail> detailList = new ArrayList<>();

int success = 0;
int fail = 0;
//解析数据
for (int rowIndex = 1; rowIndex < maxRow; rowIndex++) {
String index = ExportExcelUtil.getContent(sheet.getCell(0, rowIndex));
String menuName = ExportExcelUtil.getContent(sheet.getCell(1, rowIndex));
String menuShortName = ExportExcelUtil.getContent(sheet.getCell(2, rowIndex));
String menuNo = ExportExcelUtil.getContent(sheet.getCell(3, rowIndex));
String menuBarName = ExportExcelUtil.getContent(sheet.getCell(4, rowIndex));
String menuImgUrl = ExportExcelUtil.getContent(sheet.getCell(5, rowIndex));
String unitSz = ExportExcelUtil.getContent(sheet.getCell(6, rowIndex));
String workSz = ExportExcelUtil.getContent(sheet.getCell(7, rowIndex));
String menuRemark = ExportExcelUtil.getContent(sheet.getCell(8, rowIndex));
String menuPrices = ExportExcelUtil.getContent(sheet.getCell(9, rowIndex));
String menuXh = ExportExcelUtil.getContent(sheet.getCell(10, rowIndex));
String menuTjd = ExportExcelUtil.getContent(sheet.getCell(11, rowIndex));

MenuUploadDetail detail = new MenuUploadDetail();
detail.setMenuName(menuName);
detail.setMenuShortName(menuShortName);

MenuDetailsBean menuDetails = new MenuDetailsBean();
menuDetails.setStoreNo(storeNo);
//参数判断
//菜品名称
if (StringUtil.isEmpty(menuName)) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,菜品名称为空");
fail++;
detailList.add(detail);
continue;
} else if (menuNameList.contains(menuName)) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,系统中已经存在该名称[" + menuName + "]");
fail++;
detailList.add(detail);
continue;
} else if (menuName.length() > 20) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,该名称[" + menuName + "]长度过大");
fail++;
detailList.add(detail);
continue;
} else {
menuDetails.setMenuName(menuName);
menuNameList.add(menuName);
}

//菜品简称
if (StringUtil.isEmpty(menuShortName)) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,菜品简称为空");
fail++;
detailList.add(detail);
continue;
} else if (menuShortName.length() > 10) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,菜品简称长度过大");
fail++;
detailList.add(detail);
continue;
} else {
menuDetails.setMenuShortName(menuShortName);
}

//菜品编码
if (StringUtil.isEmpty(menuNo)) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,菜品编号为空");
fail++;
detailList.add(detail);
continue;
} else if (menuSerList.contains(menuNo)) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,系统中已经存在该编号[" + menuNo + "]");
fail++;
detailList.add(detail);
continue;
} else if (menuNo.length() > 20) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,该编号[" + menuNo + "]长度过大");
fail++;
detailList.add(detail);
continue;
} else {
menuDetails.setMenuNo(menuNo);
menuSerList.add(menuNo);
}

//判断菜品类型
if (StringUtil.isEmpty(menuBarName)) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,菜品类别为空");
fail++;
detailList.add(detail);
continue;
} else if (!barNameList.contains(menuBarName)) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,不存在菜品类别[" + menuBarName + "]");
fail++;
detailList.add(detail);
continue;
} else {
menuDetails.setMenuBarNo(menuBarMap.get(menuBarName));
}

//菜品图片 暂时不判断
if (StringUtil.isEmpty(menuImgUrl)) {
logger.info("没有图片不做处理");
} else if (!menuImgUrl.toLowerCase().endsWith(".png") && !menuImgUrl.toLowerCase().endsWith(".jpg") && !menuImgUrl.toLowerCase().endsWith(".jpeg")) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,菜品图片格式不对,只能为png、jpg、jpeg");
fail++;
detailList.add(detail);
continue;
} else {
//得到图片 判断图片的属性
File file = new File(filePath, menuImgUrl);
if (!file.exists()) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行," + menuName + "对应图片未找到");
fail++;
detailList.add(detail);
continue;
}
BufferedImage image = ImageIO.read(new FileInputStream(file));
if (StringUtil.isEmpty(image) || image.getWidth() < 400 || image.getHeight() < 400) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,图片的宽度或者图片的高度不满足尺寸要求");
fail++;
detailList.add(detail);
continue;
} else if (file.length() > 2 * 1024 * 1024) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,菜品图片大小不能超过2M");
fail++;
detailList.add(detail);
continue;
}
String fileName = FileUtils.getNewName(file.getName());

Map<String, String> map = OSSUtils.upload(fileName, new FileInputStream(file));
if (!StringUtil.isEmpty(map)) {
menuDetails.setMenuLargeImg(map.get(OSSUtils.IMAGE_URL));
menuDetails.setMenuSmallImg(map.get(OSSUtils.SMALL_IMAGE_URL));
} else {
logger.info(file.getName() + "处理失败");
}
}

//判断单位信息
if (StringUtil.isEmpty(unitSz)) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,单位设置为空");
fail++;
detailList.add(detail);
continue;
} else if (!unitNameList.contains(unitSz)) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,不存在该单位[" + unitSz + "]");
fail++;
detailList.add(detail);
continue;
} else {
menuDetails.setUintId(unitMap.get(unitSz));
}
//判断工作间
if (StringUtil.isEmpty(workSz)) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,工作间为空");
fail++;
detailList.add(detail);
continue;
} else if (!workNameList.contains(workSz)) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,不存在工作间[" + workSz + "]");
fail++;
detailList.add(detail);
continue;
} else {
menuDetails.setWorkshopId(workMap.get(workSz));
}
//菜品描述
menuDetails.setMenuContent(menuRemark);

//判断销售价格
if (StringUtil.isEmpty(menuPrices)) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,销售单价为空");
fail++;
detailList.add(detail);
continue;
} else if (!StringUtil.isNumber(menuPrices)) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,销售单价不是金额字符串");
fail++;
detailList.add(detail);
continue;
} else {
BigDecimal price = new BigDecimal(menuPrices);
if (price.compareTo(BigDecimal.ZERO) != 1) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,销售单价必须大于0");
fail++;
detailList.add(detail);
continue;
} else {
menuDetails.setPrice(price);
}
}

//排序位
if (StringUtil.isEmpty(menuXh)) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,排序位为空");
fail++;
detailList.add(detail);
continue;
} else if (!StringUtil.isInt(menuXh)) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,排序位为正整数");
fail++;
detailList.add(detail);
continue;
} else if (Integer.parseInt(menuXh) < 1) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,排序位必须大于0");
fail++;
detailList.add(detail);
continue;
} else {
menuDetails.setArrayNum(Integer.parseInt(menuXh));
}

if (StringUtil.isEmpty(menuTjd)) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,推荐度为空");
fail++;
detailList.add(detail);
continue;
} else if (!tjdMap.containsKey(menuTjd)) {
detail.setOptResult("F");
detail.setOptRemark("失败原因:第" + rowIndex + "行,不存在推荐度[" + menuTjd + "]");
fail++;
detailList.add(detail);
continue;
} else {
menuDetails.setRecommendLevel(tjdMap.get(menuTjd));
}

menuDetails.setIsDelete("N");
menuDetails.setIsMust("N");
menuDetails.setChilliLevel(0);
menuDetails.setIsSignboard("N");
menuDetails.setStatus(1);
menuDetails.setClearStatus(1);
menuDetails.setShowIcon("1");
menuDetails.setAddTime(DateUtils.getCurrentDateString());
menuDetails.setHaveTaste(0);
menuDetails.setBidPrice(new BigDecimal(0));
detail.setOptResult("Y");
detail.setOptRemark("第" + rowIndex + "行,数据验证通过");
success++;
detailList.add(detail);

//菜单List 加入
menus.add(menuDetails);
}

uploadInfo.setSuccessNum(success);
uploadInfo.setFailNum(fail);
uploadInfo.setOptNum(success + fail);
JSONObject response = new JSONObject();
response.put("successNum", success);
response.put("failNum", fail);
response.put("resultData", detailList);
result.put("respData", response);
/*
* 添加数据库到数据库  先添加 批量操作历史
* 获取批量历史Id 插入详情信息中
* 添加 成功的菜单详情
*/

//删除目录下的文件
excelFile.delete();
//添加批量历史
MenuUploadInfo uploadReturnInfo;
if (uploadInfoDao.insert(uploadInfo) > 0) {
uploadReturnInfo = uploadInfo;
} else {
logger.error("批量插入操作历史失败");
throw new Exception("批量插入操作历史失败");
}

MenuUploadInfo upload = JsonUtils.jsonToPojo(uploadReturnInfo.toString(), MenuUploadInfo.class);

for (MenuUploadDetail menuUploadDetail : detailList) {
menuUploadDetail.setUploadId(upload.getId());
}

if (!(uploadDetailDao.batchInsert(detailList) > 0)) {
logger.error("批量插入详情失败");
throw new Exception("批量插入详情失败");
}

if (menus.size() > 0) {
//插入成功的菜品
if (!(menuDetailsDao.batchAddMenu(menus) > 0)) {
logger.error("插入菜单失败");
throw new Exception("插入菜单失败");
}
}
result.put("respCode", "00");
result.put("message", "上传成功");
return result;
} catch (Exception e) {
result.put("respCode", "01");
result.put("message", e.getMessage());
logger.info("修改出错:" + e.getMessage());
e.printStackTrace();
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐