SpringBoot实现excel文件生成和下载

使用SpringBoot实现excel生成和下载,生成模板如下

controller

@RequestMapping(value = { "/downloadExcelTemplate" }, method = RequestMethod.GET)
 public String downloadExcelTemplate(HttpSession httpSession, HttpServletResponse response) {
 try {
  dealExcelService.downloadExcelTemplate(response);
  return "success";
 } catch (Exception e) {
  logger.error("downloadExcelTemplate_error", e);
  return "failure";
 }
}

service

public void downloadExcelTemplate(HttpServletResponse response) throws Exception {
 //文件名
 SimpleDateFormat format3 = new SimpleDateFormat("yyyyMMddHHmm");
 String fileName = new String(("文件名" + format3.format(new Date()) + "导入模板").getBytes(), "ISO8859_1");
 //配置请求头
 ServletOutputStream outputStream = response.getOutputStream();
 // 组装附件名称和格式
 response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");
 // 创建一个workbook 对应一个excel应用文件
 XSSFWorkbook workBook = new XSSFWorkbook();
 // 在workbook中添加一个sheet,对应Excel文件中的sheet
 XSSFSheet sheet = workBook.createSheet("模板");
 ExportUtil exportUtil = new ExportUtil(workBook, sheet);
 XSSFCellStyle headStyle = exportUtil.getHeadStyle();
 XSSFCellStyle bodyStyle = exportUtil.getBodyStyle2();
 // 构建表头
 XSSFRow headRow = ExportUtil.createRow(sheet, 0);
 XSSFCell cell;

 String[] titles = {"表头一", "表头二", "表头三"};
 int index = 0;
 for (String title : titles) {
  cell = ExportUtil.createCell(headRow, index);
  cell.setCellStyle(headStyle);
  cell.setCellValue(title);
  index++;
 }

 try {
  workBook.write(outputStream);
  outputStream.flush();
  outputStream.close();
 } catch (IOException e) {
  e.printStackTrace();
 } finally {
  try {
  outputStream.close();
  } catch (IOException e) {
  e.printStackTrace();
  }
 }
}

ExportUtil导出工具类

package com.shengsheng.utils;

import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;

/**
 * excel 表格导出工具类
 *
 * @author shengshenglalala
 */
public class ExportUtil {
 private XSSFWorkbook wb;

 private XSSFSheet sheet;

 /**
 * @param wb
 * @param sheet
 */
 public ExportUtil(XSSFWorkbook wb, XSSFSheet sheet) {
 this.wb = wb;
 this.sheet = sheet;
 }

 /**
 * 合并单元格后给合并后的单元格加边框
 *
 * @param region
 * @param cs
 */
 public void setRegionStyle(CellRangeAddress region, XSSFCellStyle cs) {

 int toprowNum = region.getFirstRow();
 for (int i = toprowNum; i <= region.getLastRow(); i++) {
  XSSFRow row = sheet.getRow(i);
  for (int j = region.getFirstColumn(); j <= region.getLastColumn(); j++) {
  XSSFCell cell = row.getCell(j);
  cell.setCellStyle(cs);
  }
 }
 }

 /**
 * 设置表头的单元格样式
 *
 * @return
 */
 public XSSFCellStyle getHeadStyle() {
 // 创建单元格样式
 XSSFCellStyle cellStyle = wb.createCellStyle();
 // // 设置单元格的背景颜色为淡蓝色
 cellStyle.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
 cellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
 // 设置单元格居中对齐
 cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
 // 设置单元格垂直居中对齐
 cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
 // 创建单元格内容显示不下时自动换行
 // cellStyle.setWrapText(true);
 // 设置单元格字体样式
 XSSFFont font = wb.createFont();
 // 设置字体加粗
 font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
 font.setFontName("宋体");
 // font.setFontHeight((short) 200);
 cellStyle.setFont(font);
 // 设置单元格边框为细线条
// cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
// cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
// cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
// cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
 return cellStyle;
 }

 /**
 * 设置表体的单元格样式
 *
 * @return
 */
 public XSSFCellStyle getBodyStyle2() {
 // 创建单元格样式
 // 创建单元格样式
 XSSFCellStyle cellStyle = wb.createCellStyle();
 // 创建单元格内容显示不下时自动换行
 // cellStyle.setWrapText(true);
 // 设置单元格字体样式
 XSSFFont font = wb.createFont();
 // 设置字体加粗
 // font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
 font.setFontName("宋体");
 font.setFontHeight((short) 200);
 font.setColor(HSSFColor.BLACK.index);
 cellStyle.setFont(font);
 // 设置单元格边框为细线条
 return cellStyle;
 }

 /**
 * 没有行,就创建行
 *
 * @param sheet
 * @param index
 * @return
 */
 public static XSSFRow createRow(XSSFSheet sheet, Integer index) {
 XSSFRow row = sheet.getRow(index);
 if (row == null) {
  return sheet.createRow(index);
 }
 return row;
 }

 /**
 * 如果没有列,就创建列
 *
 * @param row
 * @param index
 * @return
 */
 public static XSSFCell createCell(XSSFRow row, Integer index) {
 XSSFCell cell = row.getCell(index);
 if (cell == null) {
  return row.createCell(index);
 }
 return cell;
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • 详解SpringBoot文件上传下载和多文件上传(图文)

    最近在学习SpringBoot,以下是最近学习整理的实现文件上传下载的Java代码: 1.开发环境: IDEA15+ Maven+JDK1.8 2.新建一个maven工程: 3.工程框架 4.pom.xml文件依赖项 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation

  • 详解SpringBoot下文件上传与下载的实现

    SpringBoot后台如何实现文件上传下载? 最近做的一个项目涉及到文件上传与下载.前端上传采用百度webUploader插件.有关该插件的使用方法还在研究中,日后整理再记录.本文主要介绍SpringBoot后台对文件上传与下载的处理. 单文件上传 / 单文件上传 @RequestMapping(value = "/upload") @ResponseBody public String upload(@RequestParam("file") Multipart

  • springboot实现文件上传和下载功能

    spring boot 引入"约定大于配置"的概念,实现自动配置,节约了开发人员的开发成本,并且凭借其微服务架构的方式和较少的配置,一出来就占据大片开发人员的芳心.大部分的配置从开发人员可见变成了相对透明了,要想进一步熟悉还需要关注源码. 1.文件上传(前端页面): <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/lo

  • springboot整合vue实现上传下载文件

    springboot整合vue实现上传下载文件,供大家参考,具体内容如下 环境 springboot 1.5.x 完整代码下载:springboot整合vue实现上传下载 1.上传下载文件api文件 设置上传路径,如例子: private final static String rootPath = System.getProperty("user.home")+File.separator+fileDir+File.separator; api接口: 下载url示例:http://l

  • SpringBoot 导出数据生成excel文件返回方式

    一.基于框架 1.IDE IntelliJ IDEA 2.软件环境 Spring boot mysql mybatis org.apache.poi 二.环境集成 1.创建spring boot项目工程 略过 2.maven引入poi <!--数据导出依赖 excel--> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apac

  • SpringBoot 文件上传和下载的实现源码

    本篇文章介绍SpringBoot的上传和下载功能. 一.创建SpringBoot工程,添加依赖 compile("org.springframework.boot:spring-boot-starter-web") compile("org.springframework.boot:spring-boot-starter-thymeleaf") 工程目录为: Application.java 启动类 package hello; import org.springf

  • SpringBoot实现文件上传下载功能小结

    最近做的一个项目涉及到文件上传与下载.前端上传采用百度webUploader插件.有关该插件的使用方法还在研究中,日后整理再记录.本文主要介绍SpringBoot后台对文件上传与下载的处理. 单文件上传 // 单文件上传 @RequestMapping(value = "/upload") @ResponseBody public String upload(@RequestParam("file") MultipartFile file) { try { if (

  • SpringBoot实现excel文件生成和下载

    使用SpringBoot实现excel生成和下载,生成模板如下 controller @RequestMapping(value = { "/downloadExcelTemplate" }, method = RequestMethod.GET) public String downloadExcelTemplate(HttpSession httpSession, HttpServletResponse response) { try { dealExcelService.down

  • springboot+vue实现文件上传下载

    本文实例为大家分享了springboot+vue实现文件上传下载的具体代码,供大家参考,具体内容如下 一.文件上传(基于axios的简单上传) 所使用的技术:axios.springboot.vue; 实现思路:通过h5 :input元素标签进行选择文件,获取所选选择的文件路径,new fromdata对象,设置fromdata的参数,设置axios对应的请求头,最后通过axios发送post请求后端服务.后端服务同过MultipartFile进行文件接收.具体代码如下: 前端代码: 1.创建v

  • python 读取excel文件生成sql文件实例详解

    python 读取excel文件生成sql文件实例详解 学了python这么久,总算是在工作中用到一次.这次是为了从excel文件中读取数据然后写入到数据库中.这个逻辑用java来写的话就太重了,所以这次考虑通过python脚本来实现. 在此之前需要给python添加一个xlrd模块,这个模块是专门用来操作excel文件的. 在mac中可以通过easy_install xlrd命令实现自动安装模块 import xdrlib ,sys import xlrd def open_excel(fil

  • 在django项目中导出数据到excel文件并实现下载的功能

    依赖模块 xlwt下载:pip install xlwt 后台模块 view.py # 导出Excel文件 def export_excel(request): city = request.POST.get('city') print(city) list_obj=place.objects.filter(city=city) # 设置HTTPResponse的类型 response = HttpResponse(content_type='application/vnd.ms-excel')

  • SpringBoot后台实现文件上传下载

    SpringBoot后台如何实现文件上传下载? 最近做的一个项目涉及到文件上传与下载.前端上传采用百度webUploader插件.有关该插件的使用方法还在研究中,日后整理再记录.本文主要介绍SpringBoot后台对文件上传与下载的处理. 单文件上传 // 单文件上传 @RequestMapping(value = "/upload") @ResponseBody public String upload(@RequestParam("file") Multipar

  • SpringMVC下实现Excel文件上传下载

    在实际应用中,经常会遇到上传Excel或者下载Excel的情况,比如导入数据.下载统计数据等等场景.针对这个问题,我写了个基于SpringMVC的简单上传下载示例,其中Excel的处理使用Apache的POI组件. 主要依赖的包如下: <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</versi

  • SpringBoot实现Excel文件批量上传导入数据库

    Spring boot + Spring data jpa + Thymeleaf 批量插入 + POI读取 + 文件上传 pom.xml: <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <versi

  • 基于Spring Mvc实现的Excel文件上传下载示例

    最近工作遇到一个需求,需要下载excel模板,编辑后上传解析存储到数据库.因此为了更好的理解公司框架,我就自己先用spring mvc实现了一个样例. 基础框架 之前曾经介绍过一个最简单的spring mvc的项目如何搭建,传送门在这里. 这次就基于这个工程,继续实现上传下载的小例子.需要做下面的事情: 1 增加index.html,添加form提交文件 2 引入commons-fileupload.commons-io.jxl等工具包 3 创建upload download接口 4 注入mul

  • Python生成并下载文件后端代码实例

    txt文件 生成并下载txt文件: @app.route('/download', methods=['GET']) def download(): content = "long text" response = make_response(content) response.headers["Content-Disposition"] = "attachment; filename=myfilename.txt" return respons

  • Windows中使用Java生成Excel文件并插入图片的方法

    生成简单的Excel文件  在现实的办公中,我们常常会有这样一个要求:要求把报表直接用excel打开.在实习中有这样一个需求.根据所选择的资源查询用户所提供附件的全部信息并生成excel供下载.但是在查询的时候我们需要来检测用户所提供的附件里面的信息是否有错误(身份证).有错误的生成错误信息excel.      Apache的POI项目,是目前比较成熟的HSSF接口,用来处理Excel对象.其实POI不仅仅只能处理excel,它还可以处理word.PowerPoint.Visio.甚至Outl

随机推荐