依赖:

        <dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.17</version></dependency>

controller层

@ApiOperation("导出")@GetMapping(value = "/exportShopping")public Object exportQuestions(HttpServletRequest request, HttpServletResponse response,Integer orderId) throws IOException, ParseException {//其中的orderId是我查询的参数Object result = orderShoppingService.ExcelExport(request,response,orderId);return result;}

service层

public Object ExcelExport(HttpServletRequest request, HttpServletResponse response, Integer orderId) throws IOException {//根据订单的id查询出所有的商品信息OrderShoppingQueryParam queryParam = new OrderShoppingQueryParam();queryParam.setPs(1000000);queryParam.setOrderId(orderId);List<OrderShopping> list = orderShoppingMapper.listQuery(queryParam);//指定模板的路径,webapp下的update文件夹放的文件String tempPath = request.getSession().getServletContext().getRealPath("/") + "upload/" + "eng_model.xlsx";//指定生成文件的路径String path = request.getSession().getServletContext().getRealPath("/") + "upload/";//下面的是util包下的自己写的方法ExcelUtils ex = new ExcelUtils();ex.exportExcel(tempPath, path, response, list);return  null;

mybatis的查询省略不写了。

下面是util下的内容

import com.navi.user.dao.OrderShoppingMapper;
import com.navi.user.entity.OrderShopping;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;@Componentpublic class ExcelUtils {//声明一个该工具类的静态的内部对象private static ExcelUtils excelUtils;/***tempPath 模板文件路径*path 文件路径*list 集合数据*/public void exportExcel(String tempPath, String path, HttpServletResponse response, List<OrderShopping> list) {//创建一个新的fileFile newFile = createNewFile(tempPath, path);InputStream is = null;XSSFWorkbook workbook = null;XSSFSheet sheet = null;try {is = new FileInputStream(newFile);// 将excel文件转为输入流workbook = new XSSFWorkbook(is);// 创建个workbook,/* Row borderRow = sheet.createRow(2);Cell borderCell = borderRow.createCell(1);*/// 获取第一个sheetsheet = workbook.getSheetAt(0);} catch (Exception e1) {e1.printStackTrace();}if (sheet != null) {try {// 写数据FileOutputStream fos = new FileOutputStream(newFile);XSSFRow row = sheet.getRow(0);if (row == null) {row = sheet.createRow(0);}XSSFCell cell = row.getCell(0);if (cell == null) {cell = row.createCell(0);}for (int i = 0; i < list.size(); i++) {//我的模板是需要在第八行开始写,注意Excel的行跟列都是从下标0开始row = sheet.createRow(i+7); //从第8行开始//根据excel模板格式写入数据....//编码createRowAndCell(list.get(i).getCode(), row, cell, 1,workbook);//名称createRowAndCell(list.get(i).getShoppingName(), row, cell, 2,workbook);//件数createRowAndCell(list.get(i).getNumber(), row, cell, 3,workbook);//单位createRowAndCell(list.get(i).getUnit(), row, cell, 4,workbook);//单价createRowAndCell(list.get(i).getPrice(), row, cell, 5,workbook);createRowAndCell(list.get(i).getNumber()*Integer.parseInt(list.get(i).getPrice()), row, cell, 6,workbook);}workbook.write(fos);fos.flush();fos.close();// 下载InputStream fis = new BufferedInputStream(new FileInputStream(newFile));byte[] buffer = new byte[fis.available()];fis.read(buffer);fis.close();response.reset();response.setContentType("text/html;charset=UTF-8");OutputStream toClient = new BufferedOutputStream(response.getOutputStream());response.setContentType("application/x-msdownload");String newName = URLEncoder.encode("in_voice"+ ".xlsx","UTF-8");response.addHeader("Content-Disposition","attachment;filename=\"" + newName + "\"");response.addHeader("Content-Length", "" + newFile.length());toClient.write(buffer);toClient.flush();} catch (Exception e) {e.printStackTrace();} finally {try {if (null != is) {is.close();}} catch (Exception e) {e.printStackTrace();}}}// 删除创建的新文件this.deleteFile(newFile);}/***根据当前row行,来创建index标记的列数,并赋值数据*/private void createRowAndCell(Object obj, XSSFRow row, XSSFCell cell, int index,XSSFWorkbook workbook) {cell = row.getCell(index);if (cell == null) {cell = row.createCell(index);//设置边框XSSFCellStyle cellStyle = workbook.createCellStyle();cellStyle.setBorderBottom(BorderStyle.THIN); //下边框cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());cellStyle.setBorderLeft(BorderStyle.THIN);//左边框cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());cellStyle.setBorderTop(BorderStyle.THIN);//上边框cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());cellStyle.setBorderRight(BorderStyle.THIN);//右边框cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());cell.setCellStyle(cellStyle);}if (obj != null)cell.setCellValue(obj.toString());elsecell.setCellValue("");}/*** 复制文件** @param s*            源文件* @param t*            复制到的新文件*/public void fileChannelCopy(File s, File t) {try {InputStream in = null;OutputStream out = null;try {in = new BufferedInputStream(new FileInputStream(s), 1024);out = new BufferedOutputStream(new FileOutputStream(t), 1024);byte[] buffer = new byte[1024];int len;while ((len = in.read(buffer)) != -1) {out.write(buffer, 0, len);}} finally {if (null != in) {in.close();}if (null != out) {out.close();}}} catch (Exception e) {e.printStackTrace();}}/*** 读取excel模板,并复制到新文件中供写入和下载** @return*/public File createNewFile(String tempPath, String rPath) {// 读取模板,并赋值到新文件// 文件模板路径String path = (tempPath);File file = new File(path);// 保存文件的路径String realPath = rPath;// 新的文件名,导出的时候的文件名称String newFileName = "in_voice" + ".xlsx";// 判断路径是否存在File dir = new File(realPath);if (!dir.exists()) {dir.mkdirs();}// 写入到新的excelFile newFile = new File(realPath, newFileName);try {newFile.createNewFile();// 复制模板到新文件fileChannelCopy(file, newFile);} catch (Exception e) {e.printStackTrace();}return newFile;}/*** 下载成功后删除** @param files*/private void deleteFile(File... files) {for (File file : files) {if (file.exists()) {file.delete();}}}}

到此下载就结束了。

MVC使用poi根据excel模板导出文件,并通过浏览器下载。相关推荐

  1. Spring Boot poi 导出Excel表格、Txt到浏览器下载

    Spring Boot & poi 导出Excel表格.Txt到浏览器下载 原文链接:小回博客 文章目录 Spring Boot & poi 导出Excel表格.Txt到浏览器下载 一 ...

  2. POI读取Excel模板并导出大量数据

    POI读取Excel模板并导出大量数据 我在使用XSSFWorkbook读取Excel模板并导出大量数据(百万级)时,发现很长时间没有响应,debugger模式发现在读取第三四十万条数据时,程序直接停 ...

  3. java excel 模板 替换_JAVA POI替换EXCEL模板中自定义标签(XLSX版本)满足替换多个SHEET中自定义标签...

    个人说明:为了简单实现导出数据较少的EXCEL(根据自定义书签模板) 一.替换Excel表格标签方法 ``` /** * 替换Excel模板文件内容 * @param map * 需要替换的标签建筑队 ...

  4. springboot整合poi基于excel模板下载的功能实现

    现在网上有很多基于poi的excel导入导出功能实现的代码,大家都写的很好,但好像关于静态资源excel模板导出的却很少.我整理了一下项目中遇到的excel导出的功能代码,展示如下,希望有所帮助,如有 ...

  5. 使用POI读取EXCEL模板并填充数据,上传至腾讯云储存桶

    读取EXCEL模板,并填充数据生成文件 前言 一.POI导入 二.具体实现 1.制作我们的模板 2.读取模板来生成新的EXCEL 3.查看生成结果 三,传到腾讯云储存桶里 1.导入COS依赖 2.写个 ...

  6. springboot使用poi实现Excel模板的下载功能

    今天做个项目,要求下载exel模板,然后填写数据,在上传,是通过poi实现的,这里给出下载excel模板的实现方案. 首先将excel模板放到resource的根目录下,然后提供下载接口,如下: @A ...

  7. java hutool poi 基于excel模板文件,填充数据的思路

    需求 用户可下载excel模板文件,填充数据后上传,也可以下载已上传所有数据的excel,模板文件和含数据excel,都有列头及列说明:由此想到模板文件和含数据excel共用一份excel模板,下载数 ...

  8. java poi导出excel模板_POI通过模板导出EXCEL文件的实例

    一般的EXCEL导出使用POI先创建一个HSSFWorkbook,然后通过不断创建HSSFRow,HSSFCell后设置单元格内容便可以完成导出. 这次在项目中需要用到模板,导出的内容包括(1.模板中 ...

  9. poi读取excel模板,并填充数据

    一.POI介绍 Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能. 基本功能: HSSF - 提供读写 ...

最新文章

  1. wx.getLocation 的使用
  2. redis配置文件redis.conf参数说明
  3. 为什么在 Verilog HDL 设计中一定要用同步而不能用异步时序逻辑?
  4. 从hadoop框架与MapReduce模式中谈海量数据处理
  5. 透彻,在SpringBoot项目中使用Netty实现远程调用
  6. 十四、爬取天气气温,制作最低气温排行榜
  7. MapReduce分区-原理
  8. mysql 恢复root用户_mysql误删root用户恢复方案
  9. qt样式表中背景图片的使用
  10. element 组件中 el-form-item label= ‘vue介绍 (vue设置)‘ 强制换行
  11. php 转义字符处理,PHP转义与反转义字符串函数详解
  12. JVM 性能调优实战之:使用阿里开源工具 TProfiler 在海量业务代码中精确定位性能代码...
  13. Photoshop 入门教程,处理图层「1」了解图层
  14. FileZilla Server目录乱码问题的解决
  15. 计算机多窗口显示桌面,怎么同时电脑桌面打开多个excel窗口
  16. 中国人民大学与加拿大女王大学金融硕士项目不仅实现自我升华还能拿到闪亮文凭
  17. [IMX6Q]fastboot下载u-boot.bin失败提示太大原因
  18. linux上cgconfig服务,linux系统调优-Cgroups
  19. LDAP中CN,OU,DC的含义
  20. 【转】电阻屏和电容屏之 二

热门文章

  1. 高阶自动驾驶量产背后,最严监管或将加速落地
  2. CORS跨域资源共享(二):详解Spring MVC对CORS支持的相关类和API【享学Spring MVC】
  3. 记录考研英语一真题单词汇总及APP制作
  4. 织梦调用父级栏目名称
  5. CC2640R2F BLE5.0 TI-RTOS概述
  6. jdk7和jdk8HashMap主要的区别
  7. 如何编写 TypeScript 声明文件
  8. 什么是SAFe(规模化敏捷框架)3——敏捷发布火车(下)
  9. Oracle 修改表存储空间
  10. Magic Leap开发指南(5)-- Hand Tracking