首先导入依赖

 <dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-base</artifactId><version>3.0.3</version></dependency><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-web</artifactId><version>3.0.3</version> </dependency><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-annotation</artifactId><version>3.0.3</version></dependency>

通过文件的方式

public String importExcelDate(@RequestParam("file") MultipartFile file) {try {XSSFWorkbook xwb = new XSSFWorkbook(file.getInputStream());//导入.xlxs//HSSFWorkbook hwb = new HSSFWorkbook(file.getInputStream());//导入.xls//获取第一个sheet表,下标是从0开始的XSSFSheet sheet = xwb.getSheetAt(0);int sheetNum = xwb.getNumberOfSheets();//获取总共有几个sheet表List<ShelterVo> list = new ArrayList<>();//int rowNum = sheet.getPhysicalNumberOfRows();//获取有数据的行数 ,如果有数据的是第n行,前面m行没有数据,则返回n-m.int rowNum = sheet.getLastRowNum();   //获取excel最后有数据的一行为n,返回n-1.返回数据行的下标 从0开始for (int i = 1; i <= rowNum; i++) {ShelterVo vo = new ShelterVo();XSSFRow row = sheet.getRow(i); //获取excel第i行,下标从0开始,第一行的下标为0//XSSFCell cell = row.getCell(0);//获取第i行的第一个单元格if (row.getCell(0) != null) {row.getCell(0).setCellType(CellType.STRING);//设置第i行第一个单元格数据为String类型String shelterName = row.getCell(0).getStringCellValue(); //获取第一个单元格的值vo.setShelterName(shelterName);}if (row.getCell(1) != null) {row.getCell(1).setCellType(CellType.STRING);String shelterAddress = row.getCell(1).getStringCellValue();  //获取String类型的值vo.setShelterAddress(shelterAddress);}if (row.getCell(3) != null) {//对于想要获取日期的值,可以把单元格设置为日期类型,但是如果直接设置为日期类型,表格中的数据不是日期类型,则会导致数据变为1970年或者其他不准确的年份//先判断数据是否为日期类型int type = row.getCell(3).getCellType();//1为公式类型if (type != 1) {boolean isDate = DateUtil.isCellDateFormatted(row.getCell(3));if (isDate) {row.getCell(3).setCellType(CellType.FORMULA);Date setDate = row.getCell(3).getDateCellValue(); //获取日期类型的值vo.setSetTime(setDate);}}}if (row.getCell(4) != null) {row.getCell(4).setCellType(CellType.NUMERIC);double capacity = row.getCell(4).getNumericCellValue();  //获取数值类型的值vo.setCapacity((int) capacity);}list.add(vo);}return "成功";} catch (IOException e) {e.printStackTrace();return e.toString();} catch (IllegalStateException e) {e.printStackTrace();return e.toString();} catch (Exception e) {e.printStackTrace();return e.toString();}}

通过Url的方式

/**
* 读取数据Excel中的数据
*
* @param required
* @return
*/
public String importExcelDate(ExcelRequired required) {try {InputStream stream = null;stream = ExcelUploadUtil.getInputStreamByUrl(required.getUrl());int success = 0;int fail = 0;XSSFWorkbook xwb = null; // 导入.xlxsxwb = new XSSFWorkbook(stream);// 获取第一个sheet表,下标是从0开始的XSSFSheet sheet = xwb.getSheetAt(0);int sheetNum = xwb.getNumberOfSheets(); // 获取总共有几个sheet表int rowNum = sheet.getLastRowNum();   // 获取excel最后有数据的一行为n,返回n-1.返回数据行的下标 从0开始for (int i = 2; i <= rowNum; i++) {XSSFRow row = sheet.getRow(i); // 获取excel第i行,下标从0 开始, 第一行的下标为0if (row != null) {if (row.getCell(0) != null) {row.getCell(0).setCellType(CellType.STRING);String wmId = row.getCell(0).getStringCellValue();//获取字符串类型的值if (StringUtils.isNotBlank(wmId)) {// 给用户绑定角色boolean permission = setPermission(wmId, required.getActId());if (permission) {success++;continue; // 手机号或 wmId,如果两个都有值则以 wmId 为准 !} else {fail++;}}}if (row.getCell(1) != null) {row.getCell(1).setCellType(CellType.STRING);String phone = row.getCell(1).getStringCellValue();//获取字符串类型的值if (StringUtils.isNotBlank(phone)) {// 给用户绑定角色boolean permission = setPermission(phone, required.getActId());if (permission) {success++;} else {fail++;}}}}}return "成功: " + success + " 条记录,失败:" + fail + " 条记录!";}catch (Exception e) {e.printStackTrace();return e.toString();}
}

ExcelRequired

/*** 读取 Excel请求参数* Created by Lance on 2020/11/19 10:26*/
@Data
@ApiModel("读取 Excel请求参数")
public class ExcelRequired {@ApiModelProperty(value = "Excel的url地址")private String url;@ApiModelProperty(value = "活动ID")private String actId;
}

ExcelUploadUtil 工具类

public class ExcelUploadUtil {/*** 导出文件时为Writer生成OutputStream** @param fileName 文件名* @param response HttpServletResponse* @return 返回*/
public static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {try {fileName = URLEncoder.encode(fileName, "UTF-8");response.setContentType("application/vnd.ms-excel");response.setCharacterEncoding("utf8");response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");response.setHeader("Pragma", "public");response.setHeader("Cache-Control", "no-store");response.addHeader("Cache-Control", "max-age=0");return response.getOutputStream();} catch (IOException e) {throw new Exception("导出excel表格失败!", e);}
}public static String getFileName() {return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
}public static void setExcelHeader(HttpServletResponse response, Workbook workbook, String filename) {try {OutputStream out = response.getOutputStream();SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");BufferedOutputStream bufferedOutPut = new BufferedOutputStream(out);String fileNameStr = filename + format.format(new Date()) + ".xlsx";response.setContentType("application/vnd.ms-excel;charset=UTF-8");response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileNameStr, "utf-8"));bufferedOutPut.flush();workbook.write(bufferedOutPut);bufferedOutPut.close();} catch (Exception e) {e.printStackTrace();}}public static OutputStream setResponseHeader(HttpServletResponse response, String fileName) throws Exception {try {SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");response.setContentType("application/octet-stream");response.setCharacterEncoding("utf-8");response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8") + format.format(new Date()) + ".xlsx");return response.getOutputStream();} catch (Exception ex) {// 重置responsexresponse.reset();response.setContentType("application/json");response.setCharacterEncoding("utf-8");Map<String, String> map = new HashMap<String, String>();map.put("status", "failure");map.put("message", "下载文件失败" + ex.getMessage());response.getWriter().println(JSONObject.toJSONString(map));throw new BusinessException("获取文件流信息失败");}
}public static InputStream getInputStreamByUrl(String urlPath) {InputStream inputStream = null;HttpURLConnection httpURLConnection = null;try {URL url = new URL(urlPath);httpURLConnection = (HttpURLConnection) url.openConnection();httpURLConnection.setConnectTimeout(3000);httpURLConnection.setDoInput(true);httpURLConnection.setRequestMethod("GET");int responseCode = httpURLConnection.getResponseCode();if (responseCode == 200) {inputStream = httpURLConnection.getInputStream();} else {throw new BusinessException("文件下载失败");}} catch (Exception e) {throw new BusinessException("文件下载失败");}return inputStream;
}public static void setExcelOctetHeader(HttpServletResponse response, Workbook workbook, String filename) {try {OutputStream out = response.getOutputStream();SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");BufferedOutputStream bufferedOutPut = new BufferedOutputStream(out);String fileNameStr = filename + format.format(new Date()) + ".xlsx";response.setContentType("application/octet-stream;charset=utf-8");response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileNameStr, "utf-8"));bufferedOutPut.flush();workbook.write(bufferedOutPut);bufferedOutPut.close();} catch (Exception e) {e.printStackTrace();}}

获取值和设置类型时需要注意的点

  • 获取excel时 下标是从0开始的
//获取第一个sheet表
XSSFSheet sheet = xwb.getSheetAt(0);
//获取第一行
XSSFRow row = sheet.getRow(0);
//获取第一个单元格
XSSFCell cell = row.getCell(0);
  • 给单元格设置数据类型时先判断数据是否存在,单元格没有值,但是任然设置数据类型会报空指针
 //设置第一个单元格数据为String类型
if (row.getCell(0) != null) {row.getCell(0).setCellType(CellType.STRING);}//设置第三个单元格为日期类型if (row.getCell(3) != null) {//先判断数据是否为日期类型int type = row.getCell(3).getCellType();//1为公式类型if (type != 1) {boolean isDate = DateUtil.isCellDateFormatted(row.getCell(3));if (isDate) {row.getCell(3).setCellType(CellType.FORMULA);//设置第三个单元格为日期类型}}
}
//设置第四个单元格为数值类型
if (row.getCell(4) != null) {row.getCell(4).setCellType(CellType.NUMERIC);
}
  • 对于想要获取日期的值,可以把单元格设置为日期类型,但是如果直接设置为日期类型,表格中的数据不是日期类型,则会导致数据变为1970年或者其他不准确的年份
//获取String类型的值
String shelterName = row.getCell(0).getStringCellValue();
//获取日期类型的值Date setDate = row.getCell(3).getDateCellValue();//获取数值类型的值
double capacity = row.getCell(4).getNumericCellValue();

Java使用poi导入Excel相关推荐

  1. Java 使用poi导入excel,结合xml文件进行数据验证的例子(增加了jar包)

    ava 使用poi导入excel,结合xml文件进行数据验证的例子(增加了jar包) 假设现在要做一个通用的导入方法: 要求: 1.xml的只定义数据库表中的column字段,字段类型,是否非空等条件 ...

  2. java使用poi导入excel小数被四舍五入问题解决

    出现问题:使用java poi导入带有小数的数据老是被自动的四舍五入掉,导致数据出错 解决办法:使用DecimalFormat处理被导入的数据 DecimalFormat df = new Decim ...

  3. java的poi导入Excel文件

    首先看看前台写法: <form action="poi/upload.do" method="post" enctype="multipart/ ...

  4. poi导出excel写入公式_【java poi 写入Excel后读取公式值问题】poi导入excel

    java poi 写入Excel后读取公式值问题 不用改公式,只需要用cell.getNumericCellValue()获取,读出来就是正确的值了,如果你读出来的还有问题,说明你其他的地方写的还有问 ...

  5. Java结合POI清洗Excel

    Java结合POI清洗Excel 下文是Java结合POI清洗Excel的示例代码,详细内容如下: ShipEntry.java package com.liang.bi.excelmodel;pub ...

  6. java利用poi导出excel功能-附带图片导出

    java利用poi导出excel功能-附带图片导出 写在前面 最近刚离职,闲来无事,于是把上两家公司都有碰到过的需求但都没有去研究实现:即导出带图片的excel报表.于是就折腾了一下这个功能,研究出来 ...

  7. poi导入excel日期处理_POI处理Excel中各种日期格式问题

    前不久写过一篇随笔<EXCEL解析之终极方法WorkbookFactory>,提到使用WorkbookFactory来处理Excel文件数据,最近发现一个问题就是这个办法不能很好的处理各种 ...

  8. java通过poi生成excel表格(自适应列宽、合并单元格后的边框添加)

    具体java通过POI读写Excel的基本使用方法可参考: POI读写Excel的基本使用 1.项目导入依赖: <!--xls--> <dependency><group ...

  9. 如何优雅的用POI导入Excel文件

    在企业级项目开发中,要经常涉及excel文件和程序之间导入导出的业务要求,那么今天来讲一讲excel文件导入的实现.java实现对excel的操作有很多种方式,例如EasyExcel等,今天我们使用的 ...

最新文章

  1. python中四种进制的输出_Python基础语法和进制
  2. matlab实战系列之人工鱼群算法求解TSP问题原理解析(下篇源码解析)
  3. Serverless 如何落地?揭秘阿里核心业务大规模落地实现
  4. SharpZipLib压缩解压
  5. [密码学基础][每个信息安全博士生应该知道的52件事][Bristol52]43 为AES 对抗侧信道攻击的防御
  6. java 获取js html_JS获取网页中HTML元素的几种方法
  7. [JS] 001_JavaScript基础增强
  8. 微信电脑版重大更新,可以上班刷朋友圈摸鱼了
  9. 阶段3 3.SpringMVC·_03.SpringMVC常用注解_7 ModelAttribute注解
  10. Basic4IOS B4I开发原生iOS,Visual Studio中编程
  11. c语言判断不是大写字母,c语言isupper()函数如何判断字符是否为大写英文字母实例...
  12. java中CheckException和UnCheckException的区别
  13. 微信内置浏览器打开所有页面空白解决方案
  14. OpenSSL-SNI
  15. 光影学习 - 三点光照
  16. Java 比较日期/时间的大小
  17. 克莱姆V(克莱姆相关系数、克莱姆关联系数、独立系数)的MATLAB计算
  18. 有哪些大数据书籍推荐 如何系统掌握大数据
  19. TCP通讯:客户端和服务端
  20. 财产保险公司应用系统各子系统简介

热门文章

  1. Python 画图,点线图
  2. 小米高通系列清串号打开写号端口工具_小米qcn基带修复文件解决串号丢失和无信号附QCN写入工具及方法...
  3. FALSE/TRUE与false/true的区别--C++--业精于勤荒于嬉,行成于思毁于随
  4. 一个比微博热搜更适合吃瓜的平台——即时热榜
  5. SAP PP配置详解之四:工艺路线
  6. 物联网——Zigbee协议简介
  7. oracle应付账款凭证编号查找,记账凭证编号怎么填写 记账凭证编号的规则
  8. 可变数据之流水号数据的批量打印
  9. VTK:体绘制裁剪——Cropping技术
  10. Linux 文件目录压缩与解压命令