Springboot之Excel表格导出

表格导出使用的还是POI,POI的介绍请查看
https://blog.csdn.net/qq_36654629/article/details/90172911
使用前需引入poi相关依赖

<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>RELEASE</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>RELEASE</version></dependency>

表格导出工具

import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;@Service
@Transactional(rollbackFor = Throwable.class)
public class GoodsExportService {/*** @param sheetName sheet标签名称,headers第一行标题名称,list 数据* @author * @description excel 导出* @date 2019-06-27* @throws IOException*/public void exportTemplate(HttpServletResponse response, String sheetName, String[] headers, List list) throws IOException {HSSFWorkbook workbook = new HSSFWorkbook();HSSFSheet sheet = workbook.createSheet(sheetName);setTitle(headers,workbook, sheet);//新增数据行,并且设置单元格数据for(int i=0;i<list.size();i++){List clist = (List)list.get(i);HSSFRow hssfRow = sheet.createRow(i+1);for(int j=0;j<clist.size();j++){hssfRow.createCell(j).setCellValue((String)clist.get(j));}}Date date = new Date();String fileName =String.valueOf(date.getTime());fileName = fileName + ".xls";//清空responseresponse.reset();//设置response的Headerresponse.setContentType("application/vnd.ms-exce;charset=GBK");response.setCharacterEncoding("GBK");response.setHeader("content-Disposition", "attachment;filename="+ java.net.URLEncoder.encode(new String(fileName.getBytes("GBK"),"ISO-8859-1"), "GBK"));response.setDateHeader("Expires", 0);OutputStream os = new BufferedOutputStream(response.getOutputStream());//将excel写入到输出流中workbook.write(os);os.flush();os.close();}// 创建表头public void setTitle(String[] headers,HSSFWorkbook  workbook, HSSFSheet sheet) {HSSFRow row = sheet.createRow(0);// 设置为居中加粗HSSFCellStyle style = workbook.createCellStyle();HSSFFont font = workbook.createFont();style.setFont(font);// 设置表格默认列宽度为15个字节for (int i = 0; i < headers.length; i++) {HSSFCell cell = row.createCell(i);HSSFRichTextString text = new HSSFRichTextString(headers[i]);cell.setCellValue(text);cell.setCellStyle(style);}}
}

表格导入

@Service
@Transactional(rollbackFor = Throwable.class)
public class GoodsImportService {@Value("${image.uploadPath}")private String imageUploadPath;@Autowiredprivate CustomGoodsUnitService customGoodsUnitService;@Autowiredprivate CustomMerchantInfoService customMerchantInfoService;@Autowiredprivate CustomGoodsCategoryService customGoodsCategoryService;/*** 批量导入商品专用** @throws IOException* @author liyueken* @description excel 导入* @date 2019-06-27*/public List analysisExcelByGoods(HttpServletRequest request, MultipartFile file, String userId, MerchantInfo info, Boolean updownState) throws IOException, InvalidFormatException {Workbook wb = readExcel(request, file);//读取Sheet sheet = null;Row row = null;List<Goods> list = null;if (wb != null) {//用来存放表中数据list = new ArrayList<>();//获取第一个sheetsheet = wb.getSheetAt(0);//获取最大行数int rownum = sheet.getLastRowNum();for (int i = 0; i < rownum; i++) {//从第二行开始row = sheet.getRow(i + 1);if (row != null) {//第一个单元格为空,定义为最后一行if (row.getCell(0) == null) {return list;}Goods goods = new Goods();goods.setId(UUIDUtils.generator());goods.setCreateUser(userId);goods.setLastModifyUser(userId);goods.setMerchantId(info.getId());goods.setMerchantName(info.getCompanyName());goods.setState(true);goods.setGoodsType(GoodsTypeEnum.NORMAL.getCode());//设置Excel数据读入实体goods.setGoodsName(getCellFormatValue(row.getCell(0)));if (row.getCell(1) != null) {goods.setGoodsDescription(getCellFormatValue(row.getCell(1)));}if (row.getCell(2) == null) {throw new GenericException(GoodsErrorEnum.GOODS_CATEGORY.getCode(), GoodsErrorEnum.GOODS_CATEGORY.getDesc());}//=================================================//-1表示不限制库存goods.setGoodsInventory(new BigDecimal("-1"));goods.setGoodsInventoryType(GoodsInventoryTypeEnum.UNRESTRICTED.getCode());String categoryName = getCellFormatValue(row.getCell(2));boolean flag = true;String categoryFullName = "";String categoryFullId = "";String[] split = categoryName.split(",");GoodsCategory goodsCategory = customGoodsCategoryService.getByName(split[0]);if (goodsCategory == null) {//商品分类不存在异常throw new GenericException(GoodsCategoryErrorEnum.CATEGORY_ISEMPTY.getCode(), GoodsCategoryErrorEnum.CATEGORY_ISEMPTY.getDesc());}goods.setCategoryId(goodsCategory.getId());//todo 待定categoryFullName = goodsCategory.getCategoryName();categoryFullId = goodsCategory.getId();String pid = goodsCategory.getPid();while (flag) {GoodsCategory bean = customGoodsCategoryService.getEqualsIdByPid(pid);if (bean == null) {flag = false;} else {categoryFullName = bean.getCategoryName() + "," + categoryFullName;categoryFullId = bean.getId() + "," + categoryFullId;pid = bean.getPid();}}goods.setCategoryFullId(categoryFullId);goods.setCategoryFullName(categoryFullName);goods.setGoodsOriginalPrice(new BigDecimal(getCellFormatValue(row.getCell(3))));if (row.getCell(4) == null) {throw new GenericException(GoodsErrorEnum.GOODS_UNIT_ISEMPTY.getCode(), GoodsErrorEnum.GOODS_UNIT_ISEMPTY.getDesc());}String goodsUnit = getCellFormatValue(row.getCell(4));//校验单位是否符合平台规范GoodsUnit goodsUnit1 = customGoodsUnitService.checkName(goodsUnit);if (goodsUnit1 == null) {throw new GenericException(GoodsErrorEnum.GOODS_UNIT_ISEMPTY.getCode(), GoodsErrorEnum.GOODS_UNIT_ISEMPTY.getDesc());}//设置商品单位编码goods.setGoodsUnit(goodsUnit);goods.setGoodsUnitCode(goodsUnit1.getCode());goods.setGoodsMinUnit(Integer.valueOf((row.getCell(5).getStringCellValue())));goods.setGoodsSalesPrice(new BigDecimal(getCellFormatValue(row.getCell(6))));goods.setAuditState(GoodsAuditStateEnum.AUDIT_OK.getCode());goods.setIfShortage(false);//默认不缺货goods.setUpdownState(updownState);//0否1是  称重商品  默认false 0goods.setIfWeighGoods(false);if (row.getCell(9).getStringCellValue() == "1") {goods.setIfWeighGoods(true);}goods.setSupplierId(row.getCell(10).getStringCellValue());goods.setSupplierName(row.getCell(11).getStringCellValue());try {goods.setQualityGuaranteePeriod(DateUtils.format(row.getCell(12).getStringCellValue(),"yyyy/MM/dd"));} catch (ParseException e) {throw new GenericException(2011001,"日期转换异常");}if (row.getCell(13) != null) {goods.setGoodsFirstPic(row.getCell(13).getStringCellValue());} else {throw new GenericException(GoodsErrorEnum.GOODS_FIRST_PIC_ISEMPTY_ISEMPTY.getCode(),GoodsErrorEnum.GOODS_FIRST_PIC_ISEMPTY_ISEMPTY.getDesc());}list.add(goods);} else {break;}}}return list;}/*** @param file 附件* @return 文件名称* @date 2019-6-27* @author zl* @description 读取附件*/public Workbook readExcel(HttpServletRequest request, MultipartFile file) throws IOException, InvalidFormatException {String excelPath = upload(request, file);//上传excel文件File excel = new File(excelPath);InputStream in = new FileInputStream(excel);String fileName = excel.getName();Workbook wb = null;if (excel.isFile() && excel.exists()) {   //判断文件是否存在InputStream is = in;if (fileName.endsWith("xls")) {wb = new HSSFWorkbook(is);} else if (fileName.endsWith("xlsx")) {wb = WorkbookFactory.create(is);} else {throw new GenericException(AttachErrorEnum.ATTACH_TYPE_EXCEL_ERROR.getCode(), AttachErrorEnum.ATTACH_TYPE_EXCEL_ERROR.getDesc());}}return wb;}/*** @param file 附件* @return 文件名称* @date 2019-6-27* @author zl* @description 附件上传*/public String upload(HttpServletRequest request, MultipartFile file) {List<FileBean> filePath = new ArrayList<>();Calendar cal = Calendar.getInstance();String folder = "" + cal.get(Calendar.YEAR) + (cal.get(Calendar.MONTH) + 1) + cal.get(Calendar.DATE);String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI();String path = "";try {//todo 前端传递业务类型。判断能否上传String fullFileName = System.currentTimeMillis() + file.getOriginalFilename();String serveFileName = fullFileName.substring(0, fullFileName.lastIndexOf("."));String originalName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));path = imageUploadPath + File.separator + folder + File.separator + fullFileName;File target = new File(path);if (!target.getParentFile().exists()) {target.getParentFile().mkdirs();}file.transferTo(target);String fileResource = basePath + "/" + folder + "/" + fullFileName;//信息封装FileBean fileBean = new FileBean(fullFileName, originalName, fileResource, file.getContentType());//返回文件在服务器的地址filePath.add(fileBean);} catch (Exception e) {e.printStackTrace();}return path;}public static String getCellFormatValue(Cell cell) {String cellValue = null;if (cell != null) {//判断cell类型switch (cell.getCellType()) {case Cell.CELL_TYPE_NUMERIC: {cellValue = String.valueOf(cell.getNumericCellValue());break;}case Cell.CELL_TYPE_FORMULA: {//判断cell是否为日期格式if (DateUtil.isCellDateFormatted(cell)) {//转换为日期格式YYYY-mm-dd
//                        cellValue = cell.getDateCellValue();cellValue = String.valueOf(cell.getNumericCellValue());} else {//数字cellValue = String.valueOf(cell.getNumericCellValue());}break;}case Cell.CELL_TYPE_STRING: {cellValue = cell.getRichStringCellValue().getString();break;}default:cellValue = "";}} else {cellValue = "";}return cellValue;}
}

业务层实现导出具体业务

@Service
@Transactional(rollbackFor = Throwable.class)
public class MerchantGoodsService extends GoodsService {@Autowiredprivate MerchantGoodsDao merchantGoodsDao;@Autowiredprivate MerchantMerchantInfoService merchantMerchantInfoService;@Autowired@Qualifier("goodsMapStructImpl")private GoodsMapStruct goodsMapStruct;@Autowiredprivate CustomMerchantInfoService customMerchantInfoService;@Autowiredprivate GoodsExportService excelExport;/*** @Description: 批量导入商品* @Param: []* @return: void* @Author:* @Date: 2019/6/29*/public void batchImport(HttpServletRequest request, MultipartFile file, String userId) throws IOException, InvalidFormatException {//卖家MerchantInfo info = customMerchantInfoService.getByUserId(userId);//卖家添加商品默认下架状态List<Goods> list = excelImport.analysisExcelByGoods(request, file, userId, info, false);//插入merchantGoodsDao.batchInsert(list);}/*** @Description: 批量导出商品逻辑* @Param: [vo, response, userId]* @return: void* @Author: * @Date: 2019/7/15*/public void batchExport(GoodsQueryVo vo, HttpServletResponse response, String userId) throws IOException {//表头headersString[] headers = {"商品名(可修改)", "商品描述(可修改)", "所属分类", "原价", "基础单位","最小销售规格", "销售价", "审核状态(可修改,0待审核,1审核通过,2审核失败,3暂存)", "销售状态(可修改,1上架,0下架)", "是否称重(可修改,1称重,0不称)","供应商id", "供应商", "保质期", "首图url"};
//        获取所有当前卖家的未删除状态的商品List<Goods> goodsList = merchantGoodsDao.selectGoodsList(vo, userId);List<List<String>> target = new ArrayList();for (Goods goods : goodsList) {List<String> row = new ArrayList<>();row.add(goods.getGoodsName());row.add(goods.getGoodsDescription());row.add(goods.getCategoryFullName());row.add(String.valueOf(goods.getGoodsOriginalPrice()));row.add(goods.getGoodsUnit());row.add(String.valueOf(goods.getGoodsMinUnit()));row.add(String.valueOf(goods.getGoodsSalesPrice()));//审核状态Byte auditState = null;if (GoodsAuditStateEnum.AUDITING.getCode() == goods.getAuditState()) {auditState = GoodsAuditStateEnum.AUDITING.getCode();} else if (GoodsAuditStateEnum.AUDIT_FAIL.getCode() == goods.getAuditState()) {auditState = GoodsAuditStateEnum.AUDIT_FAIL.getCode();} else if (GoodsAuditStateEnum.AUDIT_OK.getCode() == goods.getAuditState()) {auditState = GoodsAuditStateEnum.AUDIT_OK.getCode();}else if (GoodsAuditStateEnum.TEMP_SAVE.getCode() == goods.getAuditState()){auditState = GoodsAuditStateEnum.TEMP_SAVE.getCode();}row.add(String.valueOf(auditState));//销售状态(上下架状态)Integer updown_state = null;if (goods.getUpdownState()) {updown_state = GoodsStateEnum.GOODS_ONLINE.getCode();} else {updown_state = GoodsStateEnum.GOODS_DOWNLINE.getCode();}row.add(String.valueOf(updown_state));//是否称重Byte ifWeight = null;if (goods.getIfWeighGoods()) {ifWeight = GoodsWeightEnum.WEIGHT.getCode();} else {ifWeight = GoodsWeightEnum.UN_WEIGHT.getCode();}row.add(String.valueOf(ifWeight));//供应商id    供应商 保质期 首图urlrow.add(goods.getSupplierId());row.add(goods.getSupplierName());if (goods.getQualityGuaranteePeriod() != null) {row.add(DateUtils.format(goods.getQualityGuaranteePeriod(), "yyyy/MM/dd"));}row.add(goods.getGoodsFirstPic());target.add(row);}String sheetName = "在售商品";excelExport.exportTemplate(response, sheetName, headers, target);}}

商品导入控制层

@Controller
@RequestMapping("goods")
public class MerchantGoodsController extends GenericController {private static final Logger LOGGER = LoggerFactory.getLogger(MerchantGoodsController.class);@Autowiredprivate FileService fileService;@Autowiredprivate MerchantGoodsService merchantGoodsService;@Autowiredprivate SecurityHandler securityHandler;/*** @Param [request, file]* @return com.hrt.framework.web.core.Result* @Author youjp* @Description //TODO 批量导入商品* @throw**/@PostMapping(value = "/goodsBatchImport")@ResponseBodypublic Result goodsBatchImport(HttpServletRequest request, MultipartFile file) throws IOException, InvalidFormatException {merchantGoodsService.batchImport(request, file, securityHandler.getUserId());return Result.success();}/*** @Param [response, vo]* @return void* @Author youjp* @Description //TODO 批量导出商品* @throw**/@GetMapping(value = "/goodsBatchExport")public void goodsBatchExport(HttpServletResponse response, GoodsQueryVo vo) throws IOException {merchantGoodsService.batchExport(vo, response, securityHandler.getUserId());}}

前端接口请求:

  • Excel导出时,只要请求导出接口即可
  var url = window.mconfig.mbaseUrl + path.goodsBatchExport + "?access_token=" + access_token + "&goodsName=" + goodsName + "&categoryFullId=" + categoryFullId;window.location.href = url;

Excel导入:

  var uploadInst2 = upload.render({elem: '#batchUploadGoods', //绑定元素accept: 'file', //普通文件exts: 'xls|xlsx', //只允许上传压缩文件url: window.mconfig.mbaseUrl + path.goodsBatchImport + "?access_token=" + access_token, //上传接口done: function (res) {if (res.code == window.httpStatus.success) {layer.msg("导入成功", {icon: 6});table.reload('goodsTableId', {url: window.mconfig.mbaseUrl + path.page,async: false,request: {pageName: 'pageNo', // 页码的参数名称,默认:pagelimitName: 'pageSize' // 每页数据量的参数名,默认:limit},page: {curr: 1},});} else {layer.alert('导入失败:' + res.msg, {icon: 0,});}},error: function () {layer.msg("请联系管理员", {icon: 5});},headers: { //通过 request 头传递Authorization: layui.data(setter.tableName)[setter.headers.accessTokenName]}});

页面代码:

      <div class="layui-input-inline"><button class="layui-btn layui-btn-normal" lay-filter="exportGoods" lay-submit=""><i class="layui-icon"></i>导出</button></div><div class="layui-btn layui-btn-sm" id="batchUploadGoods"><i class="layui-icon"></i>批量导入<span id="batchUploadTag"></span></div>

更详细的可以看一下这篇博文:
https://blog.csdn.net/typ1805/article/details/83279532

Springboot之Excel表格导出相关推荐

  1. 《springboot中实现excel表格导出》

    <springboot中实现excel表格导出> 简介 在Spring Boot中,实现Excel表格导出的方式有很多种,以下是几种常见的方法: 使用Apache POI:Apache P ...

  2. SpringBoot下载excel表格

    SpringBoot下载excel表格 git地址:https://gitee.com/benming-walnut/download-excel.git 1.目录结构 2.相关依赖 <pare ...

  3. vue数组转Excel表格导出

    vue数组转Excel表格导出 安装依赖 npm i xlsx vue组件 <template><div><el-button type="success&qu ...

  4. linux脚本的数据输出到excel,使用shell实现Excel表格导出功能 | 剑花烟雨江南

    在Web项目中,我们经常会遇到Excel表格导出的功能,对于一些数据实时性要求不高的.逻辑相对简单的导出,是否可用通过shell脚本的方式来进行导出,从而降低开发成本呢? 我们都知道,CSV格式可以用 ...

  5. js导出变量 vue_vue.js前端实现excel表格导出和获取headers里的信息

    前段时间写过一篇文章基于element实现后台管理系统,并提到excel表格导出功能,可能描述不是很详细,现在单独整理列出. 后端提供的接口: // 下载分拣列表 export function ge ...

  6. 通用Excel表格导出(Map类型数据导出为表格)

    背景 为提升代码开发效率,项目使用了通用查询(动态数据表.动态条件.动态列名等),各表查询通过同一个页面展现,前端通过获取路径上的表名调用同一个后端控制器--动态获取到查询条件.数据列名.不同表数据等 ...

  7. C# Winfrom Excel表格导出 Aspose.Cells超简单方式

    C# Winfrom Excel表格导出 Aspose.Cells超简单方式 首先需要下载 Aspose.Cells.dll,Aspose.Slides.dll,Aspose.Words.dll 这三 ...

  8. thinkphp excel表格导出

    Thinkphp里实现excel表格导出数据,需要在网上下载PHPExcel类包,放在Vendor文件夹下面 地址:http://phpexcel.codeplex.com/releases/view ...

  9. excel表格导出之后身份证号列变成了科学计数法

    excel表格导出之后身份证号列变成了科学计数法 解决:写sql查询出所有数据,并在身份证列添加字符,然后导出,将要复制的excel表格设置单元格格式问文本类型,然后复制粘贴,再把加入的字符删除,搞定 ...

最新文章

  1. 使用getopt处理shell脚本的参数
  2. 互信息 卡方 - 文本挖掘
  3. edxp显示未安装_如何在 Centos 8 / RHEL 8 上安装和配置 VNC 服务器
  4. java 三位数的水仙花数
  5. [学习笔记]c#Primer中文版-类设计、static成员、const和readonly数据成员
  6. 终于有人说清楚了!内卷和努力到底有啥区别?
  7. C 语言取整的几种方法6,C语言有以下几种取整方法:
  8. javascript之Map 和 Set
  9. 控制服务器系统设计,基于 DNS 技术的顶管机远程控制系统设计与实现
  10. Unity屏幕坐标转UI坐标
  11. 字面量(literal)与 C 语言复合字面量(compound literals)
  12. LinkedHashMap介绍
  13. 程序员职业发展路径图:从菜鸟工程师到高级架构师(转)
  14. Linux实用教程(第三版)
  15. VBA打开一个EXCEL文件并在二个文件之间来回操作的代码
  16. End-to-end/hand-crafted的含义(深度学习)
  17. 知识百科:针式打印机打印头是核心技术
  18. 排列组合 离散数学_排列组| 离散数学
  19. ❤️Python制作表白小程序,七夕能不能脱单就全靠它了!❤️(附源码)
  20. WebShell箱子简介与原理

热门文章

  1. [QualityCenter]QC是什么?发展历程是怎样?
  2. CAD字体显示问号的解决办法
  3. Deep Reinforcement Learning amidst Lifelong Non-Stationarity
  4. 【TypeScript专题】之类型断言
  5. 自动报靶系统中的靶机属于电子靶机,射击训练各项需求均可满足
  6. 【力扣刷题 | 第十一天】
  7. matlab在DSP中的应用(六)---离散傅里叶变换的性质
  8. Bandit算法学习[网站优化]04——UCB(Upper Confidence Bound) 算法
  9. SSD深度学习模型对工件裂纹进行检测
  10. Excel函数大全-09逻辑函数