POI数据导入导出Excel(样式可以自己设置)

//----------------------------Controller层 ------------------------------------------------
@Api(tags = "商品管理")
@RestController
@Slf4j
@RequestMapping("/goods")
public class GoodsController {@Autowiredprivate GoodsService GoodsService;@ApiOperation("导入信息")@PostMapping("/importGoods")public RestResult importGoods(MultipartFile file) throws Exception {return goodsService.importGoods(file);}@ApiOperation("导出信息")@GetMapping("/exportGoods")public ResponseEntity<byte[]> exportGoods(String startTime,String endTime) throws Exception {return goodsService.exportGoods(startTime,endTime);}
}
//----------------------------Service层---------------------------------------------------
public interface GoodsService extends IService<Goods> {//导入RestResult  importGoods(MultipartFile file) throws IOException;//导出ResponseEntity<byte[]> exportGoods(String startTime,String endTime) throws Exception;
}
//-----------------------------业务实现层-----------------------------------------------
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, Goods> implements GoodsService {@Autowiredprivate GoodsDao goodsDao;//导入public RestResult  importGoods(MultipartFile file) throws IOException {InputStream is = file.getInputStream();String fileName = file.getOriginalFilename();//获取工作簿Workbook hssfWorkbook = null;if (fileName.endsWith("xlsx")) {hssfWorkbook = new XSSFWorkbook(is);// Excel 2007} else if (fileName.endsWith("xls")) {hssfWorkbook = new HSSFWorkbook(is);// Excel 2003}//获取工作表的页数int numberOfSheets = hssfWorkbook.getNumberOfSheets();//利用反射获取实体类的属性名称Class clazz = Goods.class;Field[] fields = clazz.getDeclaredFields();List<Goods> list = new ArrayList<>();//获取工作表for (int i = 0; i < numberOfSheets; i++) {Sheet sheetAt = hssfWorkbook.getSheetAt(i);//获取行,确认数据是从第几行导入for (int rowNum = 2; rowNum <= sheetAt.getLastRowNum(); rowNum++) {Row hssfRow = sheetAt.getRow(rowNum);Goods goods= new Goods();/*** 此处可灵活多变处理,根据实际的Excel表格形式;主要是将数据放在list集合中* 1.也可以进行按列读取*   // 得到Excel的列数* int totalCells = 0;*   if (lastRowNum >= 1 && hssfSheet.getRow(2) != null) {*    totalCells = hssfSheet.getRow(2).getPhysicalNumberOfCells();*   }*  //循环列*  for (int cellNum = 1; cellNum <= totalCells; cellNum++) {*   budgetSettlement = new BudgetSettlement();*   for (int rowNum = 2; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {*       Row row = hssfSheet.getRow(rowNum);*       if (row != null) {*           for (Field field : fields) {*              field.setAccessible(true);*               if (StringUtils.equals(field.getName(), Constant.GOODS_LIST_ENTITY.get(rowNum - 2))) {*                   getCellValue(field, row, cellNum, goods);*               }*           }*       }*   }* }* 2.特殊的数据可以单独设置赋值* */for (Field field : fields) {//此处使用反射设置private属性可读取field.setAccessible(true);if (StringUtils.equals(field.getName(), Constant.GOODS_LIST_ENTITY.get(rowNum - 2))) {getCellValue(field, row, cellNum, goods);}}list.add(goods);}}saveBatch(list);
}/*** @Description:导入数据格式处理(无返回值)* @Author: Yrc* @Data: 2022/5/13 10:58* @Param: [field, row, cellNum, goods]* @Return: void* @Version: 1.0* Throws:*/public void getCellValue(Field field, Row row, int cellNum,  Goods goods) throws IllegalAccessException {Cell cell = ImportExportUtil.getCell(row, cellNum);Class fieldType = field.getType();if (String.class == fieldType) {if (cell.getCellTypeEnum() == CellType.STRING && Optional.ofNullable(cell).isPresent()) {field.set(goods, row.getCell(cellNum).toString());} else {field.set(goods, null);}} else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {if (cell.getCellTypeEnum() == CellType.NUMERIC && Optional.ofNullable(cell).isPresent()) {String str = row.getCell(cellNum).toString();String k = str.substring(0, str.indexOf("."));field.set(goods, Integer.parseInt(k));} else {field.set(goods, null);}} else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {if (cell.getCellTypeEnum() == CellType.NUMERIC && Optional.ofNullable(cell).isPresent()) {field.set(goods, Long.parseLong(row.getCell(cellNum).toString()));} else {field.set(goods, null);}} else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {if (cell.getCellTypeEnum() == CellType.NUMERIC && Optional.ofNullable(cell).isPresent()) {field.set(goods, Double.parseDouble(row.getCell(cellNum).toString()));} else {field.set(goods, null);}} else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {if (cell.getCellTypeEnum() == CellType.NUMERIC && Optional.ofNullable(cell).isPresent()) {field.set(goods, Float.parseFloat(row.getCell(cellNum).toString()));} else {field.set(goods, null);}} else if (Date.class == fieldType) {if (cell.getCellTypeEnum() == CellType.NUMERIC && Optional.ofNullable(cell).isPresent()) {// 如果注解指定了日期格式, 安注解指定的格式格式化Excel annotation = field.getAnnotation(Excel.class);SimpleDateFormat formatter;if (annotation != null && StringUtils.isNotBlank(annotation.dateFormat())) {formatter = new SimpleDateFormat(annotation.dateFormat());} else {// 未指定时采用默认年月日的形式格式化formatter = new SimpleDateFormat("yyyy-MM-dd");}if (row.getCell(cellNum).getDateCellValue() != null) {String dateString = formatter.format(row.getCell(cellNum).getDateCellValue());field.set(goods, dateString);}else{field.set(goods, null);}}else if(cell.getCellTypeEnum()==CellType.STRING && Optional.ofNullable(cell).isPresent()){String stringCellValue = row.getCell(cellNum).getStringCellValue();field.set(goods, stringCellValue );}else{throw new RuntimeException();}}}//导出
public ResponseEntity<byte[]> exportGoods(String startTime,String endTime) throws Exception {Optional.ofNullable(startTime).orElseThrow(() -> new CustomException("请指定导出的开始时间"));Optional.ofNullable(endTime).orElseThrow(() -> new CustomException("请指定导出的结束时间"));Workbook workbook = new XSSFWorkbook();CellStyle titleCellStyle = createCellStyle(workbook);Sheet sheet = workbook.createSheet(startTime,endTime);// 第0行,表头设置createTitleRow(sheet, startTime,endTime, titleCellStyle);/将字段名称赋值到单元格(按列设置或按行设置,根据实际需求设置)for (int cIndex = 0; cIndex < Constant.GOODS_LIST.size(); cIndex++) {row = sheet.createRow(cIndex + 3);cell = row.createCell(0);cell.setCellValue(Constant.GOODS_LIST.get(cIndex));// 给单元格赋值cell.setCellStyle(dataStyle);}//利用反射获取实体类的属性名称Class clazz = Goods.class;Field[] fields = clazz.getDeclaredFields();//将数据循环List<Goods> goodsList = goodsDao.selectByTime(startTime,endTime);for(Goods goods: goodsList ){for (int cIndex = 0; cIndex < Constant.GOODS_LIST_ENTITY.size(); cIndex++) {for (Field field : fields) {field.setAccessible(true);if (StringUtils.equals(field.getName(), Constant.GOODS_LIST_ENTITY.get(cIndex))) {row = ImportExportUtil.getRow(sheet, cIndex);cell = ImportExportUtil.getCell(row, cIndex);setCellValueByCell(cell, field, goods);}}}ByteArrayOutputStream outputStream = new ByteArrayOutputStream();workbook.write(outputStream);byte[] bytes = outputStream.toByteArray();return CommonUtils.createResponseEntity(bytes, startTime+ "-"+endTime+"购物清单.xlsx");
}/*** @Description:设置表头* @Author: Yrc* @Data: 2022/5/11 16:57* @Param: [sheet, startTime,endTime, cellStyle]* @Return: void* @Version: 1.0* Throws:*/private void createTitleRow(Sheet sheet, String startTime,String endTime,  CellStyle cellStyle) {// 第0行合并String title =startTime+ "-"+endTime+"购物清单";CellRangeAddress titleRangeAddress = new CellRangeAddress(0, 0, 0, 30);sheet.addMergedRegion(titleRangeAddress);// 设置内容Row row = ImportExportUtil.getRow(sheet, 0);row.setRowStyle(cellStyle);//设置宽度和高度row.setHeight((short) (Constant.CELL_HEIGHT_MULTIPLE * 40));sheet.setColumnWidth(0, 20 * 256);//设置列的宽度Cell titleCell = ImportExportUtil.getCell(row, 0);titleCell.setCellValue(title);// 设置样式titleCell.setCellStyle(cellStyle);
}/*** @Description:处理单元格不同类型的取值* @Author: Yrc* @Data: 2022/5/10 16:15* @Param: [cell, field, t]* @Return: void* @Version: 1.0* Throws:*/public void setCellValueByCell(Cell cell, Field field, Goods t) throws IllegalAccessException {Class fieldType = field.getType();if (String.class == fieldType) {if (field.get(t) == null) {cell.setCellValue((String) null);} else {cell.setCellValue((String) field.get(t));}} else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {if (field.get(t) == null) {cell.setCellValue((String) null);} else {cell.setCellValue((Integer) field.get(t));}} else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {if (field.get(t) == null) {cell.setCellValue((String) null);} else {cell.setCellValue((Long) field.get(t));}} else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {if (field.get(t) == null) {cell.setCellValue((String) null);} else {cell.setCellValue((Double) field.get(t));}} else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {if (field.get(t) == null) {cell.setCellValue((String) null);} else {cell.setCellValue((Float) field.get(t));}} else if (Date.class == fieldType) {// 如果注解指定了日期格式, 安注解指定的格式格式化Excel annotation = field.getAnnotation(Excel.class);SimpleDateFormat formatter;if (annotation != null && StringUtils.isNotBlank(annotation.dateFormat())) {formatter = new SimpleDateFormat(annotation.dateFormat());} else {// 未指定时采用默认年月日的形式格式化formatter = new SimpleDateFormat("yyyy-MM-dd");}if (field.get(t) != null) {String dateString = formatter.format(field.get(t));cell.setCellValue(dateString);}}}/*** @Description:表头样式设置* @Author: Yrc* @Data: 2022/5/17 15:48* @Param: [workbook]* @Return: org.apache.poi.ss.usermodel.CellStyle* @Version: 1.0* Throws:*/private CellStyle createCellStyle(Workbook workbook) {CellStyle cellStyle = workbook.createCellStyle();Font font = workbook.createFont();//字体大小font.setFontHeightInPoints((short) 15);//设置是否加粗font.setBold(true);//选择需要用到的字体格式cellStyle.setFont(font);//设置自动换行cellStyle.setWrapText(true);//设置水平居中cellStyle.setAlignment(HorizontalAlignment.CENTER);//设置垂直居中cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//设置下边框cellStyle.setBorderBottom(BorderStyle.THIN);//设置上边框cellStyle.setBorderTop(BorderStyle.THIN);//设置走边框cellStyle.setBorderLeft(BorderStyle.THIN);//设置右边框cellStyle.setBorderRight(BorderStyle.THIN);return cellStyle;}
   /*** @Description:工具类* @Author: Yrc* @Data: 2022/5/17 15:48* @Version: 1.0*/public class ImportExportUtil {/*** @Description:获取每一行单元格的数据,判断是否为空,* @Author: Yrc* @Data: 2022/4/18 17:16* @Param: [row, colIndex]* @Return: org.apache.poi.ss.usermodel.Cell* Throws:*/public static Cell getCell(Row row, int colIndex) {return Optional.ofNullable(row.getCell(colIndex)).orElseGet(() -> row.createCell(colIndex));}}public class Constant {public static final List<String> GOODS_LIST=Arrays.asList("名称","价格")public static final List<String> GOODS_LIST_ENTITY=Arrays.asList("name","price")}public class CommonUtils {/*** 用字节数组和文件名生成 ResponseEntity对象* * @param bytes  字节数组* @param fileName 文件名* @return ResponseEntity<byte>* @author Yrc* @date 2022-04-08*/public static ResponseEntity<byte[]> createResponseEntity(byte[] bytes, String fileName) throws Exception {HttpHeaders headers = new HttpHeaders();headers.setContentDispositionFormData("attachment",URLEncoder.encode(fileName, Charset.defaultCharset().name()));headers.setContentLength(bytes.length);headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);headers.setAccessControlExposeHeaders(Arrays.asList(HttpHeaders.CONTENT_DISPOSITION, HttpHeaders.CONTENT_LENGTH,HttpHeaders.CONTENT_TYPE));return ResponseEntity.status(HttpStatus.SC_OK).headers(headers).body(bytes);}public static ResponseEntity<byte[]> createResponseEntity(Workbook workbook, String fileName) throws Exception {ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();workbook.write(byteArrayOutputStream);byte[] bytes = byteArrayOutputStream.toByteArray();return CommonUtils.createResponseEntity(bytes, fileName);}}

JAVA语言(POI数据导入导出Excel)相关推荐

  1. JAVA实现数据库数据导入/导出到Excel(POI)

    原文地址为: JAVA实现数据库数据导入/导出到Excel(POI) 准备工作: 1.导入POI包:POI下载地址http://mirrors.tuna.tsinghua.edu.cn/apache/ ...

  2. MSSQL数据导入导出Excel的相关代码

    MSSQL数据导入导出Excel的相关代码 参考: https://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926 1 Export data to e ...

  3. C#窗体将DGV控件中数据导入导出Excel表

    目录 界面图: 效果视频: 一:将DGV数据导出到Excel表中 二:将Excel表数据导入到DGV中 三:界面全部代码 界面图: 效果视频: DGV数据导入导出Excel 一:将DGV数据导出到Ex ...

  4. POI实现导入导出excel

    poi在日常的导入导出中是比较常用到的,最近也总结了下接触到的poi相关的导入导出的一些代码,有问题可以指出: package com.poi;import km.org.apache.poi.hss ...

  5. Java 实现数据库数据 导入 导出成Excel文档的功能

    1.创建导入 导出工具类,写入其导入和导出方法 导出成外部文件: public static ResponseEntity<byte[]> emp2Excel(List<Emp> ...

  6. java使用POI工具类导出excel

    POI导出excel 1.导入maven依赖 <dependency><groupId>org.apache.poi</groupId><artifactId ...

  7. easypoi导出数值型_SpringBoot使用EasyPoi进行数据导入导出Excel(一)

    在实际项目开发中,对于Excel的导入导出还是很常见的需求,比如说将数据根据模板批量导入到数据库中,以及将数据库中的数据批量导出陈Excel的形式 现有需求: 下载固定的导入Excel模板 导入Exc ...

  8. java使用POI的HSSFWorkbook导出excel模板添加各种校验

    java导出excel模板添加各种校验 添加值域(下拉列) /*** @description 设置某些列的值只能输入预制的数据,显示下拉框.* @param sheet 模板sheet页(需要设置下 ...

  9. SQL语言之数据导入导出(Oracle)

    数据的导入导出(Oracle) 一.数据库导入导出需要注意 目标数据库要与资源数据库有着名称相同的表空间: 目标数据在进行导入时,用户名尽量相同(这样保证用户的权限级别相同): 目标数据库每次在 ...

最新文章

  1. android studio文件风格,Android Studio构建风格 – 如何拥有不同风格的相同源文件
  2. 腾讯云 视频 点播 视频上传接口
  3. [网络安全自学篇] 十三.Wireshark抓包原理(ARP劫持、MAC泛洪)及数据流追踪和图像抓取(二)
  4. JAX-RS 2.0的新功能– @BeanParam批注
  5. skywalking使用mysql_聊聊skywalking的mysql-plugin
  6. 20本重磅图书等你认领:前沿、创业、个人成长全有了
  7. 变与不变: Undo构造一致性读的例外情况
  8. 【Oracle】Oracle中使用转义字符
  9. 为什么只看重结果_买家下单最看重的三项服务,做好这三点,让你的销量涨涨涨...
  10. bundle adjustment原理(1)
  11. 量化指标公式源码_量化指标公式源码,通达信量化买盘潮指标
  12. java编写flash相册的制作软件,Flash电子相册制作工具(Amazing Flash Gallery Maker)
  13. 微型计算机控制技术学科认识,微型计算机控制技术学习心得.docx
  14. 我的移动开发春季历程,大厂面试题汇总
  15. Python爬虫120例之案例58,手机APP爬虫,“武器库”的准备and皮皮虾APP的测试
  16. 传奇私服服务器修改沙巴克时间,新手教程:如何修改沙巴克名称
  17. 【详细服务器配julia】
  18. pandas读取excel带汉字的列头,Pandas读取excel与中文文件名
  19. 单片机实验-数据传送
  20. 项目管理 之七 SSH、GPG 密钥生成步骤、部署 Github、Gitee 及使用效果

热门文章

  1. 谈谈网站是如何进行访问的
  2. Java面试题系列【5】Mysql经典五十问
  3. 马云创业语录 - 《赢在中国》
  4. oracle oda建立磁盘组,oracle DBA反映ODA中的虚拟机无法分配内存
  5. 计算机毕设选题推荐 SSM个人交友网站 网上交友平台 同城交友平台Java Vue MySQL数据库 远程调试 代码讲解
  6. 取消文本框被选中时边框的默认样式
  7. Arduino ESP8266控制SG90舵机输出PWM信号
  8. Microsemi的FPGA开发环境Libero编译器更换后.tcl文件问题解决办法
  9. 高性能web服务器nginx(三)之源码搭建LNMP
  10. brill标注器案例