之前的项目中有遇到上传Excel文件的需求,简单说就是解析一个固定格式的Excel表格,然后存到数据库对应的表中,表格如下:

项目采用SSM架构,mvc模式,显而易见,这个Excel表需要拆成两个表,分别存入数据库中,这种表会解析,那其他的应该就难不倒我们了。我自己写的java后台的相关解析代码如下。

注意Excel文件中每个单元格的格式要准确,否则可能解析错误,如果有更加简洁的方案,欢迎大家在留言评论区,相互学习,共同进步!

依赖文件主要是ExcelUtil,其他的直接用maven导入就好,ExcelUtil的路径:https://i.cnblogs.com/Files.aspx

package com.yuandi.car.platform.controller;

import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat; import org.apache.commons.lang.time.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
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.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile; import com.yuandi.car.common.bean.RestDataResult;
import com.yuandi.car.common.enums.ResponseEnum;
import com.yuandi.car.common.exception.ServiceException;
import com.yuandi.car.common.util.ExcelUtils;
import com.yuandi.car.common.util.UUIDutil;
import com.yuandi.car.platform.service.IManufactService;
import io.swagger.annotations.Api;
import java.util.UUID; import com.yuandi.car.platform.dao.model.T301_merchant;
import com.yuandi.car.platform.dao.model.T701_car_order;
import com.yuandi.car.platform.dao.model.T701_car_order_ext; @Controller
@RequestMapping("/order")
@Api(value = "order接口")
public class OrderController extends BaseController { private static Logger logger = LoggerFactory.getLogger(OrderController.class); @Autowired
private IManufactService manufactService; @RequestMapping(value = "/uploadDeal", method = RequestMethod.POST)
@ResponseBody
public RestDataResult uploadDeal(@RequestParam("file") MultipartFile file) {
RestDataResult result = new RestDataResult();
try {
if (validToken()) {
String contentType = file.getContentType();
String fileName = file.getOriginalFilename();
Workbook wb = WorkbookFactory.create(new ByteArrayInputStream(file.getBytes()));
Sheet sheet = wb.getSheetAt(0);
Row row = null; FormulaEvaluator formulaEvaluator = null;
if (fileName.endsWith("xlsx")) {
formulaEvaluator = new XSSFFormulaEvaluator((XSSFWorkbook) wb);
} else {
formulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook) wb);
}
T701_car_order order = new T701_car_order();
String orderid = UUIDutil.getUUID();
order.setOrderid(orderid);
//manufactService.addcarOrder(order);
String ownerEntity = null;
String mertPhone = null;
boolean flag = false;
for (int i = 1; i < 6; i++) { //i < sheet.getLastRowNum() - 0 + 1;
row = sheet.getRow(i);
if (null == row) {
continue;
} switch (i) {
case 1:
for (Cell c : row) {//循环单行的每一个空格
String value = null;
boolean isMerge = ExcelUtils.isMergedRegion(sheet, i, c.getColumnIndex());
// 判断是否具有合并单元格
if (isMerge) {
value = ExcelUtils.getMergedRegionValue(sheet, row.getRowNum(), c.getColumnIndex());
} else {
value = ExcelUtils.getCellValueFormula(c, formulaEvaluator);
} if (c.getColumnIndex() == 2) { order.setOwnerentity(value);
ownerEntity = value;
System.out.println("经销商法人姓名:" + value);
} else if (c.getColumnIndex() == 5) {
order.setMerchantphone(value);
mertPhone = value;
System.out.println("联系电话:" + value);
}
}
break;
case 2:
for (Cell c : row) {
String value = null;
boolean isMerge = ExcelUtils.isMergedRegion(sheet, i, c.getColumnIndex());
// 判断是否具有合并单元格
if (isMerge) {
value = ExcelUtils.getMergedRegionValue(sheet, row.getRowNum(), c.getColumnIndex());
} else {
value = ExcelUtils.getCellValueFormula(c, formulaEvaluator);
} if (c.getColumnIndex() == 2) { order.setManagername(value);
System.out.println("公司分管经理:" + value);
} else if (c.getColumnIndex() == 5) {
order.setManagerphone(value);
System.out.println("联系电话:" + value);
}
}
break;
case 3:
for (Cell c : row) {
String value = null;
boolean isMerge = ExcelUtils.isMergedRegion(sheet, i, c.getColumnIndex());
// 判断是否具有合并单元格
if (isMerge) {
value = ExcelUtils.getMergedRegionValue(sheet, row.getRowNum(), c.getColumnIndex());
} else {
value = ExcelUtils.getCellValueFormula(c, formulaEvaluator);
} if (c.getColumnIndex() == 2) {
order.setMerchantname(value);
System.out.println("经销商全称:" + value);
} else if (c.getColumnIndex() == 5) {
order.setAddress(value);
System.out.println("收货地址:" + value);
}
}
break;
case 4:
for (Cell c : row) {
String value = null;
boolean isMerge = ExcelUtils.isMergedRegion(sheet, i, c.getColumnIndex());
// 判断是否具有合并单元格
if (isMerge) {
value = ExcelUtils.getMergedRegionValue(sheet, row.getRowNum(), c.getColumnIndex());
} else {
value = ExcelUtils.getCellValueFormula(c, formulaEvaluator);
} if (c.getColumnIndex() == 2) { Double f = Double.valueOf(value);
Integer intvalue = (int)Math.ceil(f);
order.setCapacity(intvalue);
System.out.println("经销商库容:" + intvalue);
} else if (c.getColumnIndex() == 5) { Date expDate = ExcelUtils.stringToNormalDate(value);
order.setExptime(expDate);
System.out.println("期望发货时间:" + expDate);
}
}
break;
case 5:
for (Cell c : row) {
String value = null;
boolean isMerge = ExcelUtils.isMergedRegion(sheet, i, c.getColumnIndex());
// 判断是否具有合并单元格
if (isMerge) {
value = ExcelUtils.getMergedRegionValue(sheet, row.getRowNum(), c.getColumnIndex());
} else {
value = ExcelUtils.getCellValueFormula(c, formulaEvaluator);
} if (c.getColumnIndex() == 2) {
order.setMonopolize(value);
System.out.println("经销商品牌经营:" + value);
}
else if (c.getColumnIndex() == 5) {
order.setBrandnumber(value);
System.out.println("品牌经营数量:" + value);
}
}
break;
} }
for (int i = sheet.getLastRowNum() - 3 + 1; i < sheet.getLastRowNum() - 0 + 1; i++) { //i < sheet.getLastRowNum() - 0 + 1;
row = sheet.getRow(i);
if (null == row) {
continue;
} switch (i - sheet.getLastRowNum()-1) {
case -3:
for (Cell c : row) {
String value = null;
boolean isMerge = ExcelUtils.isMergedRegion(sheet, i, c.getColumnIndex());
// 判断是否具有合并单元格
if (isMerge) {
value = ExcelUtils.getMergedRegionValue(sheet, row.getRowNum(), c.getColumnIndex());
} else {
value = ExcelUtils.getCellValueFormula(c, formulaEvaluator);
} if (c.getColumnIndex() == 2) {
// TODO
//Integer intvalue = Integer.parseInt(value);
Double f = Double.valueOf(value);
Integer intvalue = (int)Math.ceil(f);
order.setTotal(intvalue);
System.out.println("合计:" + value + " 辆");
} else if (c.getColumnIndex() == 5) {
//Long f = Long.valueOf(value);Long f = Long.parseLong(value);
BigDecimal bd=new BigDecimal(value); order.setTotalprice(bd);
System.out.println("总价:" + value + " 元");
}
}
break; case -2:
for (Cell c : row) {
String value = null;
boolean isMerge = ExcelUtils.isMergedRegion(sheet, i, c.getColumnIndex());
// 判断是否具有合并单元格
if (isMerge) {
value = ExcelUtils.getMergedRegionValue(sheet, row.getRowNum(), c.getColumnIndex());
} else {
value = ExcelUtils.getCellValueFormula(c, formulaEvaluator);
} if (c.getColumnIndex() == 2) {
// TODO
order.setOrganizername(value);
System.out.println("编制人姓名:" + value);
} else if (c.getColumnIndex() == 4) {
order.setOrganizerphone(value);
System.out.println("编制人电话:" + value);
} else if (c.getColumnIndex() == 6) {
Date subTime = ExcelUtils.stringToNormalDate(value);
order.setSubmittime(subTime);
System.out.println("订单提报时间:" + subTime);
}
}
break;
case -1:
for (Cell c : row) {//循环单行的每一个空格
String value = null;
boolean isMerge = ExcelUtils.isMergedRegion(sheet, i, c.getColumnIndex());
// 判断是否具有合并单元格
if (isMerge) {
value = ExcelUtils.getMergedRegionValue(sheet, row.getRowNum(), c.getColumnIndex());
} else {
value = ExcelUtils.getCellValueFormula(c, formulaEvaluator);
} if (c.getColumnIndex() == 2) {
order.setRegulatorname(value);
System.out.println("接收人姓名:" + value);
} else if (c.getColumnIndex() == 4) {
order.setRegulatorphone(value);
System.out.println("接收人电话:" + value);
} else if (c.getColumnIndex() == 6) {
Date receiveTime = ExcelUtils.stringToNormalDate(value);
order.setReceivetime(receiveTime);
System.out.println("订单接收确认时间:" + receiveTime);
}
}
break;
} }
if(ownerEntity.isEmpty()||mertPhone.isEmpty()){
result.setRespcode(ResponseEnum.PARAM_NULL.getCode());
result.setMessage(ResponseEnum.PARAM_NULL.getMessage());
}else{
T301_merchant merchant = manufactService.qryMerchantByOwnerPhone(ownerEntity, mertPhone);
Date now = new Date();
order.setManufactid(merchant.getEntityid());
order.setName(merchant.getEntityname());
order.setMerchantid(merchant.getMerchantid());
order.setCreatetime(now); manufactService.addcarOrder(order);
flag = true;
}
//以下内容添加到扩展表
for (int i = 7; i < sheet.getLastRowNum() - 3 + 1; i++) {
row = sheet.getRow(i);
if (null == row) {
continue;
}
T701_car_order_ext orext = new T701_car_order_ext();
orext.setOrderid(orderid);
for (Cell c : row) {
String value = null;
boolean isMerge = ExcelUtils.isMergedRegion(sheet, i, c.getColumnIndex());
// 判断是否具有合并单元格
if (isMerge) {
value = ExcelUtils.getMergedRegionValue(sheet, row.getRowNum(), c.getColumnIndex());
} else {
value = ExcelUtils.getCellValueFormula(c, formulaEvaluator);
} if (c.getColumnIndex() == 2) {
orext.setModel(value);
} else if (c.getColumnIndex() == 3) {
orext.setVersion(value);
} else if (c.getColumnIndex() == 4) {
Double f = Double.valueOf(value);
Integer intvalue = (int)Math.ceil(f);
orext.setTotal(intvalue);
System.out.println("数量:" + value + " 辆");
} else if (c.getColumnIndex() == 5) {
BigDecimal bd=new BigDecimal(value);
orext.setUnitprice(bd);
System.out.println("单价:" + bd + " 元");
} else if (c.getColumnIndex() == 6) {
//Long f = Long.valueOf(value);Long f = Long.parseLong(value);
BigDecimal bd=new BigDecimal(value);
orext.setTotalprice(bd);
System.out.println("金额:" + value + " 元");
} else if (c.getColumnIndex() == 7) {
orext.setProperty(value);
System.out.println("属性:" + value);
}
}
if(flag){
manufactService.addcarOrderExt(orext); }else{
result.setRespcode(ResponseEnum.PARAM_NULL.getCode());
result.setMessage(ResponseEnum.PARAM_NULL.getMessage());
}
} setSucc(result);
} else {
setInvalidToken(result);
}
} catch (ServiceException e) {
result.setCodeMessage(e.getErrorCode(), e.getMessage());
} catch (Exception e) {
logger.error("", e);
result.setRespcode(ResponseEnum.SYS_ERROR.getCode());
result.setMessage(ResponseEnum.SYS_ERROR.getMessage());
}
return result;
}
}  

Java:Excel文件上传至后台的更多相关文章

  1. java实现文件上传下载

    喜欢的朋友可以关注下,粉丝也缺. 今天发现已经有很久没有给大家分享一篇技术文章了,于是想了一下给大家分享一篇java实现文件上传下载功能的文章,不喜欢的希望大家勿喷. 想必大家都知道文件的上传前端页面 ...

  2. java进行文件上传,带进度条

    网上看到别人发过的一个java上传的代码,自己写了个完整的,附带源码 项目环境:jkd7.tomcat7. jar包:commons-fileupload-1.2.1.jar.commons-io-1 ...

  3. Java Web文件上传

    参考资料:http://www.cnblogs.com/xdp-gacl/p/4200090.html 一.问题描述 Java Web文件上传需要借助一些第三方库,常用的是借助Apache的包,有两个 ...

  4. [SAP ABAP开发技术总结]客户端文本文件、Excel文件上传下载

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

  5. [SAP ABAP开发技术总结]文本文件、Excel文件上传下传

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

  6. CentOS下安装配置NFS并通过Java进行文件上传下载

    1:安装NFS (1)安装 yum install nfs-utils rpcbind (2)启动rpcbind服务 systemctl restart rpcbind.service 查看服务状态 ...

  7. Java实现文件上传到服务器(FTP方式)

    Java实现文件上传到服务器(FTP方式) 1,jar包:commons-net-3.3.jar 2,实现代码: //FTP传输到数据库服务器 private boolean uploadServer ...

  8. Java Web文件上传原理分析(不借助开源fileupload上传jar包)

    Java Web文件上传原理分析(不借助开源fileupload上传jar包) 博客分类: Java Web   最近在面试IBM时,面试官突然问到:如果让你自己实现一个文件上传,你的代码要如何写,不 ...

  9. Java超大文件上传解决办法

    这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数 下面直接贴代码吧,一些难懂的我大部分都加上注释了: 上传文件实体类: 看得 ...

随机推荐

  1. oracle函数 months_between(d1,d2)

    [功能]:返回日期d1到日期d2之间的月数. [参数]:d1,d2 日期型 [返回]:数字 如果d1>d2,则返回正数 如果d1<d2,则返回负数 [示例] select sysdate, ...

  2. HZOJ 砍树

    考试时打了个暴力T40,正解是整除分块???完全没听过……而且这题居然还有人A了…… 整除分块 暴力就不说了,直接上正解: 将d除过去,右边向下取整(显然不能向上取整啊,会超k的)这个不用处理,整除就 ...

  3. Project Euler Problem 26-Reciprocal cycles

    看样子,51nod 1035 最长的循环节 这道题应该是从pe搬过去的. 详解见论文的(二)那部分:http://web.math.sinica.edu.tw/math_media/d253/2531 ...

  4. OP_REQUIRES failed at conv_ops.cc:386 : Resource exhausted: OOM when allocating tensor with shape..

    tensorflow-gpu验证准确率是报错如上: 解决办法: 1. 加入os.environ['CUDA_VISIBLE_DEVICES']='2' 强制使用CPU验证-----慢 2.'batch ...

  5. codedecision P1113 同颜色询问 题解 线段树动态开点

    题目描述:https://www.cnblogs.com/problems/p/11789930.html 题目链接:http://codedecision.com/problem/1113 这道题目 ...

  6. Python--day61--Django ORM单表操作之展示用户列表

    user_list.html views.py 项目的urls.py文件

  7. Python--day41--线程池--python标准模块concurrent.futures

    1,线程池代码示例:(注:进程池的话只要将以下代码中的ThreadPoolExecutor替换成ProcessPoolExecutor即可,这里不演示) import time from concur ...

  8. SVN常用命令之checkout

    官方解释,请参考:http://www.subversion.org.cn/svnbook/nightly/svn.ref.svn.c.checkout.html 常用检出命令: svn co htt ...

  9. 代码片段 修改Windows用户名

    cmd /c wmic useraccount where name=' 记录防备忘

  10. Spring Security 学习笔记-授权控制过滤器

    FilterSecurityInterceptor  是比较核心的过滤器,主要负责授权工作.SecurityMetadataSource 需要安全授权的元数据资源 AuthenticationMana ...