Springboot Excle导入导出

导入操作:Excle批量导入

导出操作:下载模版

开发笔记


pom.xml

        <!-- Excle相关jar -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<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.4</version>
</dependency>

工具类

ExcleUtils:

package com.wechat.cwbt.util;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; 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.web.multipart.MultipartFile; /**
*
*
* @Package: com.wechat.cwbt.util
* @ClassName: ExcleUtils
* @Description:Excle相关工具
* @author: zk
* @date: 2019年8月30日 下午4:29:22
*/
public final class ExcleUtils {
/**
*
* @description Excle导入
* @author zk
* @date 2019年8月30日
* @param file
* @return 返回数据对象格式为: 表头->数据
*/
public static Map<String, Object> getDataList(MultipartFile file){
Map<String, Object> result = new HashMap<String, Object>();
// System.out.println(file.getName()+"\t"+file.getOriginalFilename());
List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>(); //判断Excel文件是否有内容
boolean notNull=false;
String filename=file.getOriginalFilename();
if (!filename.matches("^.+\\.(?i)(xls)$") && !filename.matches("^.+\\.(?i)(xlsx)$")) {
result.put("msg","上传文件格式不正确!");
result.put("SUCCESS", false);
return result;
}
//判断Excel文件的版本
boolean isExcel2003=true;
if (filename.matches("^.+\\.(?i)(xlsx)$")) {
isExcel2003 = false;
}
Workbook wb = null;
try {
InputStream fis=file.getInputStream();
if (isExcel2003) {
wb = new HSSFWorkbook(fis);
} else {
wb = new XSSFWorkbook(fis);
}
} catch (Exception e) {
e.printStackTrace();
} // 总共有多少张sheet表
int sheetnum = wb.getNumberOfSheets();
//判断有无数据
if(sheetnum == 1) {
Sheet sheet = wb.getSheetAt(0);
// 第一行数据数据
int rowNum = sheet.getPhysicalNumberOfRows();
if(rowNum==1){
result.put("msg","无数据");
result.put("SUCCESS", false);
return result;
}
}
//获取数据
for (int i = 0; i < sheetnum; i++) {
Sheet sheet = wb.getSheetAt(i);
// 表头数据
Row namerow = sheet.getRow(0); // 第一行数据
Row headrow = sheet.getRow(1); if (null != headrow) { // 总行数
int rowNum = sheet.getPhysicalNumberOfRows();
// int rowNum = sheet.getLastRowNum();
// System.out.println(file.getName() + "共:" + rowNum + " 行!"); // 总列数
int colNum = headrow.getPhysicalNumberOfCells(); // 判断工作表是否为空
if (rowNum == 0) {
continue;
} // 循环行
for (int j = 1; j <= rowNum; j++) {
Row row = sheet.getRow(j);
if (null != row) { Map<String, Object> rowmap = new HashMap<String, Object>();
for(int h=0;h<colNum;h++) {
String str1 = namerow.getCell(h).getStringCellValue();
row.getCell(h).setCellType(Cell.CELL_TYPE_STRING);//设置Cell的类型,按照String取出数据
String str2 = row.getCell(h).getStringCellValue();
rowmap.put(str1,str2);
}
dataList.add(rowmap); //continue;
}
}
}
}
result.put("data", dataList);
result.put("SUCCESS", true);
return result;
} /**
*
* @description Excle导出
* @author zk
* @date 2019年8月30日
* @param filename 文件名称
* @param namearr 表头
* @param datalist 数据
* @return
*/
public static Workbook exportDailyBill(String filename,String[] namearr,List<Map<String, Object>> datalist){
// 创建excel工作簿
Workbook workbook = new XSSFWorkbook();
// 创建第一个sheet(页),并命名
Sheet sheet = workbook.createSheet(filename);
//设置首行标题标题
Row row = sheet.createRow(0);
for(int i=0;i<namearr.length;i++) {
row.createCell(i).setCellValue(namearr[i]);
}
if(datalist!=null) {
//新增数据行,并且设置单元格数据
int rowNum = 1;
for(Map<String, Object> data : datalist)
{
row = sheet.createRow(rowNum);
for(int i=0;i<namearr.length;i++) {
row.createCell(i).setCellValue((String)data.get(namearr[i]));
}
rowNum++;
}
}
return workbook;
}
}

调用:

controller:

   /**
*
* @description 下载模版
* @author zk
* @date 2019年9月9日
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping("/downloadExcle")
public void downloadExcle(HttpServletRequest request, HttpServletResponse response)throws Exception{
String fileName = "按键录入表";//文件名
String[] namearr = {"按键类型","按键名称","按键编码"};//标题
List<Map<String, Object>> datalist = null;//数据
Workbook workbook = ExcleUtils.exportDailyBill(fileName, namearr, datalist);
String name = new String(fileName.getBytes("utf-8"), "ISO-8859-1");//处理文件名称
response.setContentType("application/octet-stream;charset=ISO8859-1");
response.setHeader("Content-disposition", "attachment;filename=" + name + ".xlsx");
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
OutputStream out = response.getOutputStream();
workbook.write(response.getOutputStream());
out.flush();
out.close();
}     /**
     *
     * @description 批量导入Excle
     * @author 左坤
     * @date 2019年9月10日
     * @param file
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Transactional
    @RequestMapping("/importExcle")
    @ResponseBody
    public Map<String, Object> importExcle(MultipartFile file,HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> result = new HashMap<String, Object>();
        Map<String, Object> resmap = ExcleUtils.getDataList(file);
        if((boolean)resmap.get("SUCCESS")) {//有数据
            List<Map<String, Object>> list = (List<Map<String, Object>>) resmap.get("data");
            List<Keyboard> keyboardlist = new ArrayList<Keyboard>();
            if(list!=null) {
                for(int i=0;i<list.size();i++) {
                    Map<String, Object> mapstr = list.get(i);
                    Keyboard keyboard = new Keyboard();
                    keyboard.setName((String)mapstr.get("按键名称"));
                    keyboard.setKeycode(Integer.parseInt((String)mapstr.get("按键编码")));
                    keyboard.setTypeid((String)mapstr.get("按键类型"));
                    keyboard.setCreatetime(new Date());
                    keyboard.setUpdatetime(new Date());
                    keyboard.setIsshow("0");
                    keyboard.setIsdel("0");
                    keyboardlist.add(keyboard);
                }
                int count = keyboardService.insertlist(keyboardlist);//成功条数
                if(count<keyboardlist.size()) {//成功条数小于插入条数
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
                    result.put("SUCCESS", false);
                    result.put("msg", "Excle第"+(count+2)+"行存在问题");
                    return result;
                }
                result.put("SUCCESS", true);
                result.put("msg", "操作成功");
            }
        }else {//无数据
            result.put("SUCCESS", false);
            result.put("msg", "Excle无数据");
        }
        return result;
    }

结束

最新文章

  1. commons-httpclient中的超时设置
  2. 微信要革&quot;传统电视&quot;的命吗?
  3. jquery.cookie.js 的使用
  4. SqlSever基础 select cast 将一个int类型数据转换为char
  5. ios assetlibrary
  6. asp.net 下OnClientClick的妙用
  7. SRM470 - SRM474(1-250pt,500pt)(471-500pt为最短路,474-500pt未做)
  8. Java equals的一个坑
  9. MongoDB安装心得
  10. JavaScript学习笔记(十一)——闭包
  11. PHP7的新功能
  12. Node.js JXcore 打包
  13. Spring MVC 学习总结(一)——MVC概要与环境配置(IDea与Eclipse示例)
  14. Matting任务里的Gradient与Connectivity指标
  15. FPGA中带优先级的if else if与不带优先级的case的探讨
  16. centos6.5下配置django+uwsgi+nginx
  17. 查询SQL执行情况
  18. oracle11gR2 手工创建基于asm存储的oracle实例
  19. PAT A1102 Invert a Binary Tree (25 分)——静态树,层序遍历,先序遍历,后序遍历
  20. VUE2.0 饿了吗视频学习笔记(七-终):compute,循环,flex,display:table

热门文章

  1. linux部署jdk-tomcat
  2. 「NOI2017」游戏 解题报告
  3. 【Flutter学习】页面布局之列表和表格处理
  4. CDN技术之--该技术概述
  5. vue2 — vuex状态管理
  6. 如何查看red gate安装时的log
  7. Tomcat负载均衡、调优核心应用进阶学习笔记(三):LNMT nginx+tomcat、LAMT apache+tomcat、session会话保持、不错的站点
  8. Normal&#160;Equation&#160;Algorithm
  9. Django框架(二十九)—— 跨域问题
  10. python_ 模块 json pickle shelve