最近要做个前端网页上传excel,数据直接添加到数据库的功能。。在此写个读取excel的demo。

首先新建springboot的web项目 导包,读取excel可以用poi也可以用jxl,这里本文用的是poi

poi的 pom依赖如下:

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency> <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>

service层的实现类为:

@Service
public class ExcelServiceImpl implements ExcelService {
@Autowired
private CorpTaxService corpTaxService; @Override
public void read(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
String fileName = "";
String filePath = "D://";
if (file != null && !file.isEmpty()){
fileName = file.getOriginalFilename();
}else {
throw new CECException(501, "上传的文件为空,请重新选择。");
}
BigDecimal tenThsoud = new BigDecimal(10000);
ArrayList<CorpTax> list = new ArrayList<>(); //excel文件路径
// String excelPath2 = "F:\\工作簿2.xlsx";
try {
FileInputStream fis = null;
if (file != null && !file.isEmpty()) { //判断文件是否存在 String[] split = file.getOriginalFilename().split("\\."); //.是特殊字符,需要转义!!!!!
Workbook wb;
//根据文件后缀(xls/xlsx)进行判断
if ( "xls".equals(split[1])){
//fis = new FileInputStream(excel); //文件流对象
wb = new HSSFWorkbook(file.getInputStream());
}else if ("xlsx".equals(split[1])){
wb = new XSSFWorkbook(file.getInputStream());
}else {
System.out.println("文件类型错误!");
throw new CECException(501, "文件类型错误");
} //开始解析
Sheet sheet = wb.getSheetAt(0); //读取sheet 0 int firstRowIndex = sheet.getFirstRowNum()+1; //第一行是列名,所以不读
int lastRowIndex = sheet.getLastRowNum();
System.out.println("firstRowIndex: "+firstRowIndex);
System.out.println("lastRowIndex: "+lastRowIndex); for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) { //遍历行
System.out.println("rIndex: " + rIndex);
Row row = sheet.getRow(rIndex);
if (row != null) {
CorpTax corpTax = new CorpTax();
corpTax.setCorpName(row.getCell(0).getStringCellValue());
corpTax.setTaxData(new BigDecimal(row.getCell(1).getNumericCellValue()).divide(tenThsoud, 6, RoundingMode.HALF_UP));
corpTax.setFiscalRet(new BigDecimal(row.getCell(2).getNumericCellValue()).divide(tenThsoud, 6,RoundingMode.HALF_UP));
corpTax.setIndustry(row.getCell(3).toString());
corpTax.setCorpType(row.getCell(4).toString());
corpTax.setCorpBelong(row.getCell(5).toString());
corpTax.setCorpYear((int)row.getCell(6).getNumericCellValue());
corpTax.setCorpMonth((int)row.getCell(7).getNumericCellValue());
System.out.println(corpTax);
list.add(corpTax);
              // 往数据库库添加数据,这里就是一个王数据库的添加操作
int insert = corpTaxService.insert(corpTax);
System.out.println(insert); int firstCellIndex = row.getFirstCellNum();
int lastCellIndex = row.getLastCellNum();
for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) { //遍历列
Cell cell = row.getCell(cIndex);
if (cell != null) {
System.out.println(cell.toString());
}
}
}
}
wb.close(); } else {
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
e.printStackTrace();
}
      // 把excel生成到指定位置进行备份。
FileInputStream fileInputStream;
try {
fileInputStream = (FileInputStream) file.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
FileOutputStream fileOutputStream = new FileOutputStream(filePath + fileName);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
byte[] bytes = new byte[1024];
while (bufferedInputStream.read(bytes) != -1){
bufferedOutputStream.write(bytes);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
bufferedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
} for (CorpTax corpTax : list){
System.out.println(corpTax);
} } public List<CorpTax> test(){
BigDecimal tenThsoud = new BigDecimal(10000);
ArrayList<CorpTax> list = new ArrayList<>(); //excel文件路径 String excelPath2 = "F:\\工作簿2.xlsx";
try {
FileInputStream fis = null;
//String encoding = "GBK";
File excel = new File(excelPath2);
if (excel.isFile() && excel.exists()) { //判断文件是否存在 String[] split = excel.getName().split("\\."); //.是特殊字符,需要转义!!!!!
Workbook wb;
//根据文件后缀(xls/xlsx)进行判断
if ( "xls".equals(split[1])){
fis = new FileInputStream(excel); //文件流对象
wb = new HSSFWorkbook(fis);
}else if ("xlsx".equals(split[1])){
wb = new XSSFWorkbook(excel);
}else {
System.out.println("文件类型错误!");
return null;
} //开始解析
Sheet sheet = wb.getSheetAt(0); //读取sheet 0 int firstRowIndex = sheet.getFirstRowNum()+1; //第一行是列名,所以不读
int lastRowIndex = sheet.getLastRowNum();
System.out.println("firstRowIndex: "+firstRowIndex);
System.out.println("lastRowIndex: "+lastRowIndex); for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) { //遍历行
System.out.println("rIndex: " + rIndex);
Row row = sheet.getRow(rIndex);
if (row != null) {
CorpTax corpTax = new CorpTax();
corpTax.setCorpName(row.getCell(0).getStringCellValue());
corpTax.setTaxData(new BigDecimal(row.getCell(1).getNumericCellValue()).divide(tenThsoud, 6, RoundingMode.HALF_UP));
corpTax.setFiscalRet(new BigDecimal(row.getCell(2).getNumericCellValue()).divide(tenThsoud, 6,RoundingMode.HALF_UP));
corpTax.setIndustry(row.getCell(3).toString());
corpTax.setCorpType(row.getCell(4).toString());
corpTax.setCorpBelong(row.getCell(5).toString());
corpTax.setCorpYear((int)row.getCell(6).getNumericCellValue());
corpTax.setCorpMonth((int)row.getCell(7).getNumericCellValue());
System.out.println(corpTax);
list.add(corpTax);
// int insert = corpTaxService.insert(corpTax); int firstCellIndex = row.getFirstCellNum();
int lastCellIndex = row.getLastCellNum();
for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) { //遍历列
Cell cell = row.getCell(cIndex);
if (cell != null) {
System.out.println(cell.toString());
}
}
}
}
wb.close();
// fis.close();
} else {
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}

上面这个实现类包含两个方法,上面的那个方法是,可以把excel生成到D盘进行备份,并且读取其中的数据,添加到数据库的(这里读取excel中的数据添加到数据库,是我根据自己的数据库格式,剪切了excel就只剩下了8列,而且每一列的格式都是手动处理的,并没有使用工具类进行处理,网友想要用工具类进行处理,可以参考https://www.cnblogs.com/zhanghaoliang/p/6526089.html)。

controller层就是一个简单的对service层的调用

@RequestMapping("excel")
@RestController
public class ExcelController { @Autowired
private ExcelService excelService; @RequestMapping(value = "upload",method = RequestMethod.POST)
public String upLoadExcel(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "file") MultipartFile file){
excelService.read(request, response, file);
return "ok";
} }

参考文章:https://www.cnblogs.com/zhanghaoliang/p/6526089.html

https://blog.csdn.net/gxx_csdn/article/details/79085713

https://www.cnblogs.com/cx-code/p/9111336.html

下面说一下,过程中的坑;

1 org.springframework.beans.BeanInstantiationException  这是因为

HttpServletRequest request, HttpServletResponse response  写成了
HttpRequest request, HttpResponse response

postman上传excel,java后台读取excel生成到指定位置进行备份,并且把excel中的数据添加到数据库的更多相关文章

  1. uploadify前台上传文件,java后台处理的例子

    1.先创建一个简单的web项目upload (如图1-1) 2.插件的准备 (1).去uploadify的官网下载一个uploadify插件,然后解压新建个js文件夹放进去(这个不强求,只要路径对了就 ...

  2. 通过JAVA对FTP服务器连接,上传,下载,读取,移动文件等

    记录一次对FTP服务器文件内容 通过Java程序对FTP服务器文件处理:连接,上传,下载,读取,移动文件等. 需求描述:今天接到一个任务,在Java项目中,读取FTP服务器上的一些文件,进行一些业务操 ...

  3. 求超大文件上传方案( Java )

    最近遇见一个需要上传百兆大文件的需求,调研了七牛和腾讯云的切片分段上传功能,因此在此整理前端大文件上传相关功能的实现. 在某些业务中,大文件上传是一个比较重要的交互场景,如上传入库比较大的Excel表 ...

  4. 记录一次node中台转发表单上传文件到后台过程

    首发掘金 记录一次node中台转发表单上传文件到后台过程 本篇跟掘金为同一个作者leung   公司几个项目都是三层架构模式即前台,中台(中间层),后台.前台微信端公众号使用vue框架,后台管理前端使 ...

  5. 从app上传图片到php,再上传到java后端服务器的方法一览

    在现在的网络开发中,上传图片类的需求实在是太普通不过了,但是对于怎么样做到上传图片,对于刚开始建立项目的时候,还是有点不知所措的.也许有幸,我们做的项目是之前已经有人写过类似的用例了,那么我们只需要依 ...

  6. 从app上传图片到php,再上传到java后端服务器的方法一条龙服务

    在现在的网络开发中,上传图片类的需求实在是太普通不过了,但是对于怎么样做到上传图片,对于刚开始建立项目的时候,还是有点不知所措的.也许有幸,我们做的项目是之前已经有人写过类似的用例了,那么我们只需要依 ...

  7. 接口测试-Http状态码-postman上传文件

    转自:https://www.cnblogs.com/jiadan/articles/8546015.html 一. 接口   接口:什么是接口呢?接口一般来说有两种,一种是程序内部的接口,一种是系统 ...

  8. vue图片上传及java存储图片(亲测可用)

    1.前言 在使用elementui的upload组件时,我一直无法做到上传的图片和其他数据一起提交.单纯的上传文件,java的存储图片的方式也有局限性. 我知道的后端保存图片有两种方式:一种是直接存储 ...

  9. java后台读取/解析 excel表格

    需求描述 前台需要上传excel表格,提交到后台,后台解析并返回给前台,展示在前台页面上! 前台部分代码与界面 <th style="padding: 7px 1px;width:15 ...

随机推荐

  1. 二叉树&满二叉树与完全二叉树

    二叉树的定义 二叉树(Binary Tree)是n(n≥0)个元素的有限集合,该集合为空或者为由一个称为"根"的元素及两个不相交的.被分别称为左子树和右子树的二叉树组成 二叉树的基 ...

  2. 浅谈javascript中的递归和闭包

    递归和闭包作为js中很重要的一环,几乎在前端的面试中都会涉及,特别闭包.今天前端组的组长冷不丁的问了我一下,粗略的回答了一下,感觉不太满足,于是重新学习了一下,写下本篇. 在说这个两个概念之前,我们先 ...

  3. python在linux中import cv2问题

    python中import cv2遇到的错误及安装方法标签 1 错误: ImportError: libXext.so.6: cannot open shared object file: No su ...

  4. SSRF绕过IP限制方法总结

    SSRF绕过IP限制方法总结 - Summary of SSRF methods for bypassing IP restrictions -https://www.cnblogs.com/iAmS ...

  5. js 数组 去重 算法(转载)

    以下内容可能有重复部分,项目有用上,但还没来得急整理和验证. 一:https://www.cnblogs.com/jiayuexuan/p/7527055.html 1.遍历数组法 它是最简单的数组去 ...

  6. three.js展示三维模型

    1.概要 最近学习Three.js,尝试加载一些3d max导出的obj.stl模型,在展示模型的时候遇到了一些问题,模型的尺寸.位置和旋转角度每次都靠手工调整,非常的不方便,就想着写一个方法来随心所 ...

  7. 微信小程序中使用云开发获取openid

    微信小程序获取openid 新建一个微信小程序项目 注意要注册一个自己的小程序账号,并有属于自己的appid 点击云开发按钮,自行填入开发环境名称 打开app.js,找到依赖环境 修改为刚才设置的环境 ...

  8. 一个97年测试妹纸的成长经历,转正直接涨薪2K

    这篇文章,涉及测试团队管理.测试流程建设.测试从业者能力成长.优秀测试从业者的状态.以及同样是两年的Tester,为何他人如此优秀 . 一切的一切,都是有原因的 . 期望这篇文章,对关注「简尚」公号的 ...

  9. PAT上机注意事项

    PAT上机注意事项 这次上机PAT遇到了很多问题,进行一下总结 1.进入考场后,检查机器是否完好,尤其是键盘的键是否失灵,以及是否有打开的页面(考试开始,打开页面都算违规) 2.关于选择IDE 部分考 ...

  10. mysql开发相关

    1.mysql事务原理,特性,事务并发控制2.如何解决高并发场景下的插入重复3.乐观锁和悲观锁4.常用数据库引擎之间区别5.mysql索引6.B-Tree7.mysql索引类型8.什么时候创建索引9. ...