第一步,vue使用el-upload组件
:action是执行上传动作的后台接口 , :limit 是上传的文件数量,el-button是触发上传的按钮。
accept=".xlsx,.xls" 是限制上传的文件格式
<template>
<div>
<el-upload
ref="upload"
action="doUpload"
accept=".xlsx,.xls"
:limit="1"
:before-upload="beforeUpload">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<a href="./static/moban.xlsx" rel="external nofollow" download="模板"><el-button size="small" type="success">下载模板</el-button></a>
<div slot="tip" class="el-upload__tip">只能上传excel文件,且不超过5MB</div>
<div slot="tip" class="el-upload-list__item-name">{{fileName}}</div>
</el-upload>
<el-button @click="visible = false">取消</el-button>
<el-button type="primary" @click="submitUpload()">确定</el-button>
</div>
</template>
<script>
export default {
data() {
return {
files: "",
fileName: "",
wronglist: "",
msg: ""
};
},
methods: {
beforeUpload(file){
//
},
submitUpload() {
//提交方法
}
}
};
</script>
效果图如下所示 :
如果需要在在上传时再次校验文件格式是否为excel,则需要在:before-upload这个钩子绑定相应的方法来校验,代码如下:
beforeUpload(file){
console.log(file,'文件');
this.files = file;
const format= file.name.split('.')[1] === 'xls'
const format2= file.name.split('.')[1] === 'xlsx'
const isLt2M = file.size / 1024 / 1024 < 5
if (!format&& !format2) {
this.$message.warning('上传模板只能是 xls、xlsx格式!')
return
}
if (!isLt2M) {
this.$message.warning('上传模板大小不能超过 5MB!')
return
}
this.fileName = file.name;
return false // 返回false不会自动上传
},
第三步,文件上传提交方法
submitUpload() {
if(this.fileName == ""){
this.$message.warning('请选择要上传的文件!')
return false
}
// 当后端接收的参数有多个时使用下面的格式
let fileFormData = new FormData();
//filename是键,file是值,就是要传的文件,test.zip是要传的文件名
fileFormData.append('file', this.files, this.fileName);
fileFormData.append('storeid','11');
fileFormData.append('discount','10');
this.$http({
url: this.$http.adornUrl("/generator/importexcel/uploadExcel"),
method: "post",
// 文件上传的请求头信息应和后台接收的参数类型保持一致
contentType: 'multipart/form-data',
data: fileFormData
}).then((res) => {
//以下就根据自己实际情况的返回参数进行判断是否导入数据库成功与否了
console.log("哈哈哈哈")
var map = res.data.wronglist // 这里接收的是一个数组对象
var arr = []
for (let i in map) { // 循环数组对象并添加到数组arr中
arr.push(map[i]);
}
console.log("哈哈哈")
})
}
以上vue前端部分代码书写完毕
以下是后台处理代码:
第一步 业务逻辑层接口:
public interface ImportExcelService {
String[] getBankListByExcel(InputStream inputStream, String fileName, int storeid, int discount);
}
第二步 业务逻辑层实现类:
package io.renren.modules.generator.importExcel;
import io.renren.modules.generator.dao.BookDao;
import io.renren.modules.generator.dao.BookDepotDao;
import io.renren.modules.generator.dao.BooktransactionDao;
import io.renren.modules.generator.entity.BookEntity;
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;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
@Service
@SuppressWarnings("unchecked")
public class ImportExcelServiceImpl implements ImportExcelService {
private final BookDao bookDao; // 店铺-图书表
@Autowired
public ImportExcelServiceImpl(BookDao bookDao){
this.bookDao=bookDao;
}
@Override
public String[] getBankListByExcel(InputStream inputStream, String fileName,int storeid,int discount) {
List list = new ArrayList<>();
Map map=new HashMap();
try{
//创建Excel工作薄
Workbook work = getWorkbook(inputStream, fileName);
Sheet sheet = null;
Row row = null;
Cell cell = null;
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if (sheet == null) {
continue;
}
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<>();
for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
li.add(cell);
}
list.add(li);
}
}
}catch (Exception e){
e.printStackTrace();
throw new RuntimeException("读取excel文件异常!!!");
}
String[] listmap;
// list
listmap= insertBooks(list,storeid,discount); //解析数据并导入数据库
return listmap;
}
// 将获取到的数据集合添加到数据库中
public String[] insertBooks( List list,int storeid,int discount){
List<List<Object>> lists=list;
String[] str=new String[list.size()]; // 将添加失败的图书以数组对象返回给前端
for (int i = 0; i < lists.size(); i++) {
BookEntity bookEntity=new BookEntity();
List<Object> lo = lists.get(i);
String barcode=lo.get(0).toString();// 获取barcode
String title=lo.get(1).toString();// 获取书名
map.put("barcode",barcode);
map.put("title",title);
int i=bookDao.insert(map)
if(i<=0){
str[i]=title;
}
}
return str;
}
/**
* 判断文件格式
*
* @param inStr
* @param fileName
* @return
* @throws Exception
*/
public Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
Workbook workbook = null;
// 获取文件后缀
String suffixName = fileName.substring(fileName.lastIndexOf("."));
if(suffixName.equals(".xls" )!=false && suffixName.equals(".xlsx")!=false) {
throw new RuntimeException("请上传正确的excel文件!");
}
// 获取文件类型
String fileType = fileName.substring(fileName.lastIndexOf("."));
if (".xls".equals(fileType)) {
workbook = new HSSFWorkbook(inStr);
} else if (".xlsx".equals(fileType)) {
workbook = new XSSFWorkbook(inStr);
} else {
throw new RuntimeException ("请上传excel文件!");
}
return workbook;
}
}
第三步 controller类:
package io.renren.modules.generator.controller;
import io.renren.common.utils.R;
import io.renren.modules.generator.importExcel.ImportExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.util.*;
/**
* excel上传
*
* @author jln
* @date 2019-08-06 10:20:02
*/
@RestController
@RequestMapping("generator/importexcel")
public class ImportControlle {
@Autowired
private ImportExcelService importExcelService;
@ResponseBody
@RequestMapping("/uploadExcel")
// 前端传入的文件参数名的定义应和此处的file保持一致
public R uploadExcel(@RequestParam(value="storeid") String storeid,
@RequestParam(value="discount") String discount,
@RequestParam(value="file") MultipartFile file, HttpServletRequest request) throws Exception {
String[] str=null;
String msg="";
if (file.isEmpty()) {
System.out.println("获取excl文件异常");
throw new RuntimeException("获取excl文件异常");
}
String path="/ImportExcel/";
try {
String fileName = file.getOriginalFilename();
//获取文件大小
long size = file.getSize();
File dest = new File(path + fileName);
if (!dest.getParentFile().exists()) {
//先得到文件的上级目录,并创建上级目录,在创建文件
//mkdirs方法可以在不知道偶没有父类文件夹的情况下创建文件夹,而mkdir必须在有父类的文件夹下创建文件
dest.getParentFile().mkdirs();
//创建文件
dest.createNewFile();
}
// 获得输入流: 读取
InputStream inputStream = file.getInputStream();
str = importExcelService.getBankListByExcel(
inputStream, file.getOriginalFilename(),
Integer.valueOf(storeid),Integer.valueOf(discount)
);
inputStream.close();
}catch (Exception e){
e.printStackTrace();
throw new RuntimeException("文件上传异常!!!");
}
return R.ok().put("wronglist",str);
}
}
postman 测试结果:
pom.xml 依赖配置
<!--文件上传组件-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<!--读取excel文件-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.9</version>
</dependency>