首先导入poi包
<!--excel poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.1</version>
</dependency>
静态资源
public class publicStc {
public static String [] studentTab={"学生信息"};
public static String[] studentTitle={"学生编号","学生姓名","学生年龄",};
public static String [] clazzTab={"班级信息"};
public static String[] clazzTitle={"班级编号","班级名称"};
public static String[] studentProperty = {"name", "age"};
public static String[] clazzProperty={"name"};
}
excel导入
Controller层
@PostMapping(value = "/upload")
public String uploadExcel(HttpServletRequest request){
String msg="";
try {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("filename");
if(isNotNull(file)){
return "文件不能为空!";
}
InputStream inputStream = file.getInputStream();
msg=studentService.getBankListByExcel(inputStream,file.getOriginalFilename());
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return msg;
}
Service层
@Transactional
@Override
public String getBankListByExcel(InputStream inputStream, String filName) {
List<String[]> listProperty=new ArrayList<>();
List<String[]> listTab=new ArrayList<>();
listProperty.add(publicStc.studentProperty);
listProperty.add(publicStc.clazzProperty);
listTab.add(publicStc.studentTab);
listTab.add(publicStc.clazzTab);
Map<String,List<Map<String,Object>>> map= ExcelUtil.getExcelDate(inputStream,filName,listProperty,listTab);
Set<String> keys = map.keySet();
for (String key: keys) {
switch (key) {
case "学生信息":
studentMapper.saveStudent(map.get(key));
break;
case "班级信息":
clazzmapper.insertClazz(map.get(key));
break;
default:
break;
}
}
return "导入成功";
}
ExcelUtil,这个地方是没法保证导入的excel是恶意的excel(脏数据),但是有一点,大家要清楚,excel导入一些场景是不存在的,存在大多数是后台的。虽然没能完全保证数据有效性,但是我这里做了一个sheet名称的验证。
public static Map<String,List<Map<String,Object>>> getExcelDate(InputStream inputStream, String filName, List<String[]> Property, List<String[]> listTab){
Map<String,List<Map<String,Object>>> resultmap=new HashMap<>();
try {
Workbook work =getWorkbook(inputStream,filName);
if (null == work) {
throw new Exception("创建Excel工作薄为空!");
}
Sheet sheet;
Row row;
Cell cell;
for (int i = 0; i < work.getNumberOfSheets(); i++) {
List<Map<String,Object>> list=new ArrayList<>();
sheet = work.getSheetAt(i);
if (sheet == null||(!sheet.getSheetName().equals(listTab.get(i)[0]))) {
continue;
}
for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
row = sheet.getRow(j);
if (row == null || row.getFirstCellNum() == j) {
continue;
}
Map<String,Object> map=new HashMap<>();
for (int y = row.getFirstCellNum(); y < Property.get(i).length; y++) {
cell = row.getCell(y);
map.put(Property.get(i)[y],cell.toString());
}
list.add(map);
}
resultmap.put(listTab.get(i)[0],list);
}
} catch (Exception e) {
e.printStackTrace();
}
return resultmap;
}
excel导出
Controller层
@GetMapping(value = "/exportexcel")
public void exportExcel(HttpServletResponse response){
try {
String[] args={"学生信息","班级信息"};
studentService.exportExcel(response,args);
} catch (IOException e) {
e.printStackTrace();
}
}
Service层
@Override
public void exportExcel(HttpServletResponse response,String[] args) throws IOException {
List<String[]> tab=new ArrayList<>();
List<String[]> title =new ArrayList<>();
List<List<Map<String,Object>>> list=new ArrayList<>();
for (int i = 0; i <args.length; i++) {
switch(args[i]){
case "学生信息":
tab.add(publicStc.studentTab);
title.add(publicStc.studentTitle);
list.add(studentMapper.getStudentList());
break;
case "班级信息":
tab.add(publicStc.clazzTab);
title.add(publicStc.clazzTitle);
list.add(clazzmapper.getClazzList());
break;
default:
break;
}
}
ExcelUtil.exportExcel(response,list,tab,title);
}
ExcelUtil,这个不需要担心excel文件名称乱码,这个问题我已经解决。
public static void exportExcel(HttpServletResponse response,List<List<Map<String,Object>>> list,List<String []> tab,List<String []> title) throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook();
for (int p = 0; p < tab.size(); p++) {
for (int i = 0; i <tab.get(p).length; i++) {
HSSFSheet sheet = workbook.createSheet(tab.get(p)[i]);
sheet.setDefaultColumnWidth(10);
HSSFCellStyle headerStyle = workbook.createCellStyle();
headerStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
HSSFRow headrow = sheet.createRow(0);
for (int j = 0; j <title.get(p).length; j++) {
HSSFCell cell = headrow.createCell(j);
HSSFRichTextString text = new HSSFRichTextString(title.get(p)[j]);
cell.setCellValue(text);
cell.setCellStyle(headerStyle);
}
for (int j = 0; j <list.get(p).size(); j++) {
HSSFRow row1 = sheet.createRow(j+1);
Set<String> key = list.get(p).get(j).keySet();
int colum=0;
for(String s : key){
row1.createCell(colum++).setCellValue(new HSSFRichTextString(list.get(p).get(j).get(s).toString()));
}
}
}
}
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setHeader("content-disposition", "attachment;filename=" + new String("中心小学".getBytes(), "ISO8859-1") + ".xls" );
response.flushBuffer();
workbook.write(response.getOutputStream());
}
想要源码请留言