1、添加POI依赖

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

2、创建EXCEL实体类

package com.example.demo.model;

import java.io.Serializable;
import java.util.List; public class ExcelData implements Serializable { private static final long serialVersionUID = 6133772627258154184L;
/**
* 表头
*/
private List<String> titles; /**
* 数据
*/
private List<List<Object>> rows; /**
* 页签名称
*/
private String name; public List<String> getTitles() {
return titles;
} public void setTitles(List<String> titles) {
this.titles = titles;
} public List<List<Object>> getRows() {
return rows;
} public void setRows(List<List<Object>> rows) {
this.rows = rows;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}

3、创建表格工具类

package com.example.demo.core.utils;

import com.example.demo.model.ExcelData;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder.BorderSide; import javax.servlet.http.HttpServletResponse;
import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List; public class ExcelUtils { /**
* 使用浏览器选择路径下载
* @param response
* @param fileName
* @param data
* @throws Exception
*/
public static void exportExcel(HttpServletResponse response, String fileName, ExcelData data) throws Exception {
// 告诉浏览器用什么软件可以打开此文件
response.setHeader("content-Type", "application/vnd.ms-excel");
// 下载文件的默认名称
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "utf-8"));
exportExcel(data, response.getOutputStream());
} public static int generateExcel(ExcelData excelData, String path) throws Exception {
File f = new File(path);
FileOutputStream out = new FileOutputStream(f);
return exportExcel(excelData, out);
} private static int exportExcel(ExcelData data, OutputStream out) throws Exception {
XSSFWorkbook wb = new XSSFWorkbook();
int rowIndex = 0;
try {
String sheetName = data.getName();
if (null == sheetName) {
sheetName = "Sheet1";
}
XSSFSheet sheet = wb.createSheet(sheetName);
rowIndex = writeExcel(wb, sheet, data);
wb.write(out);
} catch (Exception e) {
e.printStackTrace();
} finally {
//此处需要关闭 wb 变量
out.close();
}
return rowIndex;
} private static int writeExcel(XSSFWorkbook wb, Sheet sheet, ExcelData data) {
int rowIndex = 0;
writeTitlesToExcel(wb, sheet, data.getTitles());
rowIndex = writeRowsToExcel(wb, sheet, data.getRows(), rowIndex);
autoSizeColumns(sheet, data.getTitles().size() + 1);
return rowIndex;
} /**
* 设置表头
*
* @param wb
* @param sheet
* @param titles
* @return
*/
private static int writeTitlesToExcel(XSSFWorkbook wb, Sheet sheet, List<String> titles) {
int rowIndex = 0;
int colIndex = 0;
Font titleFont = wb.createFont();
//设置字体
titleFont.setFontName("simsun");
//设置粗体
titleFont.setBoldweight(Short.MAX_VALUE);
//设置字号
titleFont.setFontHeightInPoints((short) 14);
//设置颜色
titleFont.setColor(IndexedColors.BLACK.index);
XSSFCellStyle titleStyle = wb.createCellStyle();
//水平居中
titleStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
//垂直居中
titleStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
//设置图案颜色
titleStyle.setFillForegroundColor(new XSSFColor(new Color(182, 184, 192)));
//设置图案样式
titleStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
titleStyle.setFont(titleFont);
setBorder(titleStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0)));
Row titleRow = sheet.createRow(rowIndex);
titleRow.setHeightInPoints(25);
colIndex = 0;
for (String field : titles) {
Cell cell = titleRow.createCell(colIndex);
cell.setCellValue(field);
cell.setCellStyle(titleStyle);
colIndex++;
}
rowIndex++;
return rowIndex;
} /**
* 设置内容
*
* @param wb
* @param sheet
* @param rows
* @param rowIndex
* @return
*/
private static int writeRowsToExcel(XSSFWorkbook wb, Sheet sheet, List<List<Object>> rows, int rowIndex) {
int colIndex;
Font dataFont = wb.createFont();
dataFont.setFontName("simsun");
dataFont.setFontHeightInPoints((short) 14);
dataFont.setColor(IndexedColors.BLACK.index); XSSFCellStyle dataStyle = wb.createCellStyle();
dataStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
dataStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
dataStyle.setFont(dataFont);
setBorder(dataStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0)));
for (List<Object> rowData : rows) {
Row dataRow = sheet.createRow(rowIndex);
dataRow.setHeightInPoints(25);
colIndex = 0;
for (Object cellData : rowData) {
Cell cell = dataRow.createCell(colIndex);
if (cellData != null) {
cell.setCellValue(cellData.toString());
} else {
cell.setCellValue("");
}
cell.setCellStyle(dataStyle);
colIndex++;
}
rowIndex++;
}
return rowIndex;
} /**
* 自动调整列宽
*
* @param sheet
* @param columnNumber
*/
private static void autoSizeColumns(Sheet sheet, int columnNumber) {
for (int i = 0; i < columnNumber; i++) {
int orgWidth = sheet.getColumnWidth(i);
sheet.autoSizeColumn(i, true);
int newWidth = (int) (sheet.getColumnWidth(i) + 100);
if (newWidth > orgWidth) {
sheet.setColumnWidth(i, newWidth);
} else {
sheet.setColumnWidth(i, orgWidth);
}
}
} /**
* 设置边框
*
* @param style
* @param border
* @param color
*/
private static void setBorder(XSSFCellStyle style, BorderStyle border, XSSFColor color) {
style.setBorderTop(border);
style.setBorderLeft(border);
style.setBorderRight(border);
style.setBorderBottom(border);
style.setBorderColor(BorderSide.TOP, color);
style.setBorderColor(BorderSide.LEFT, color);
style.setBorderColor(BorderSide.RIGHT, color);
style.setBorderColor(BorderSide.BOTTOM, color);
}
}

4、创建ExcelConstant

package com.example.demo.core.constant;

public class ExcelConstant {

    /**
* 生成文件存放路径
*/
public static final String FILE_PATH = "C:\\Users\\Administrator\\Desktop\\"; /**
* 表格默认名称
*/
public static final String FILE_NAME = "TEST.xls";
}

5、创建ExcelController

package com.example.demo.controller;

import com.example.demo.core.aop.AnnotationLog;
import com.example.demo.core.constant.ExcelConstant;
import com.example.demo.core.ret.RetResponse;
import com.example.demo.core.ret.RetResult;
import com.example.demo.core.ret.ServiceException;
import com.example.demo.core.utils.ExcelUtils;
import com.example.demo.model.ExcelData;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*; import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List; @RestController
@RequestMapping("excel")
public class ExcelController { @Resource
private UserInfoService userInfoService; @PostMapping("/test")
public RetResult<Integer> test(){
int rowIndex = 0;
List<UserInfo> list = userInfoService.selectAlla(0, 0);
ExcelData data = new ExcelData();
data.setName("hello");
List<String> titles = new ArrayList();
titles.add("ID");
titles.add("userName");
titles.add("password");
data.setTitles(titles); List<List<Object>> rows = new ArrayList();
for(int i = 0, length = list.size();i<length;i++){
UserInfo userInfo = list.get(i);
List<Object> row = new ArrayList();
row.add(userInfo.getId());
row.add(userInfo.getUserName());
row.add(userInfo.getPassword());
rows.add(row);
}
data.setRows(rows);
try{
rowIndex = ExcelUtils.generateExcel(data, ExcelConstant.FILE_PATH + ExcelConstant.FILE_NAME);
}catch (Exception e){
e.printStackTrace();
}
return RetResponse.makeOKRsp(Integer.valueOf(rowIndex));
} @GetMapping("/test2")
public void test2(HttpServletResponse response){
int rowIndex = 0;
List<UserInfo> list = userInfoService.selectAlla(0, 0);
ExcelData data = new ExcelData();
data.setName("hello");
List<String> titles = new ArrayList();
titles.add("ID");
titles.add("userName");
titles.add("password");
data.setTitles(titles); List<List<Object>> rows = new ArrayList();
for(int i = 0, length = list.size();i<length;i++){
UserInfo userInfo = list.get(i);
List<Object> row = new ArrayList();
row.add(userInfo.getId());
row.add(userInfo.getUserName());
row.add(userInfo.getPassword());
rows.add(row);
}
data.setRows(rows);
try{
ExcelUtils.exportExcel(response,"test2",data);
}catch (Exception e){
e.printStackTrace();
}
}
}




原文地址:Mr_初晨

Spring Boot:添加导出Excel表格功能的更多相关文章

  1. spring boot poi 导出Excel

    public class ExcelData implements Serializable { private static final long serialVersionUID = 444401 ...

  2. spring mvc项目中导出excel表格简单实现

    查阅了一些资料,才整理出spring mvc 项目导出excel表格的实现,其实很是简单,小计一下,方便以后查阅,也希望帮助有需要的朋友. 1.导入所需要依赖(Jar包).我使用的是maven,所以坐 ...

  3. Spring Boot 导出Excel表格

    Spring Boot 导出Excel表格 添加支持 <!--添加导入/出表格依赖--> <dependency> <groupId>org.apache.poi& ...

  4. PHP导入导出excel表格图片(转)

    写excel的时候,我用过pear的库,也用过pack压包的头,同样那些利用smarty等作的简单替换xml的也用过,csv的就更不用谈了.呵呵.(COM方式不讲了,这种可读的太多了,我也写过利用wp ...

  5. EasyUi通过POI 实现导出xls表格功能

    Spring +EasyUi+Spring Jpa(持久层) EasyUi通过POI 实现导出xls表格功能 EasyUi界面: 点击导出按钮实现数据导入到xls表格中 第一步:修改按钮事件: @Co ...

  6. PHP导入导出excel表格图片的代码和方法大全

    基本上导出的文件分为两种: 1:类Excel格式,这个其实不是传统意义上的Excel文件,只是因为Excel的兼容能力强,能够正确打开而已.修改这种文件后再保存,通常会提示你是否要转换成Excel文件 ...

  7. Element-ui组件库Table表格导出Excel表格

    安装npm install --save xlsx file-saver 两个插件的详细地址在下面 https://github.com/SheetJS/js-xlsxhttps://github.c ...

  8. java导出excel表格

    java导出excel表格: 1.导入jar包 <dependency> <groupId>org.apache.poi</groupId> <artifac ...

  9. NPOI导出excel表格应用

    最近接到一个需求,在原有系统上做二次开发 ,要求导出DataGridView数据到Excel表格中.要求如下: 兼容所有excel版本: 导出后excel各列的样式,字段类型不变. 成型如下:

随机推荐

  1. IdentityServer4 之Client Credentials走起来

    前言 API裸奔是绝对不允许滴,之前专门针对这块分享了jwt的解决方案(WebApi接口裸奔有风险):那如果是微服务,又怎么解决呢?每一个服务都加认证授权也可以解决问题,只是显得认证授权这块冗余,重复 ...

  2. redis基础-Remote Dictionary Server

    Redis支持多个数据库,并且每个数据库的数据是隔离的不能共享,并且基于单机才有,如果是集群就没有数据库的概念. Redis默认支持16个数据库(可以通过配置文件支持更多,无上限),可以通过配置dat ...

  3. 项目API接口鉴权流程总结

    权益需求对接中,公司跟第三方公司合作,有时我们可能作为甲方,提供接口给对方,有时我们也作为乙方,调对方接口,这就需要API使用签名方法(Sign)对接口进行鉴权.每一次请求都需要在请求中包含签名信息, ...

  4. 初识sa-token,一行代码搞定登录授权!

    前言 在java的世界里,有很多优秀的权限认证框架,如Apache Shiro.Spring Security 等等.这些框架背景强大,历史悠久,其生态也比较齐全. 但同时这些框架也并非十分完美,在前 ...

  5. 【MySQL 基础】MySQL必知必会

    MySQL必知必会 简介 <MySQL必知必会>的学习笔记和总结. 书籍链接 了解SQL 数据库基础 什么是数据库 数据库(database):保存有组织的数据的容器(通常是一个文 件或一 ...

  6. 牛客网NC15二叉树的层次遍历

    题目 给定一个二叉树,返回该二叉树层序遍历的结果,(从左到右,一层一层地遍历) 例如: 给定的二叉树是{3,9,20,#,#,15,7}, 该二叉树层序遍历的结果是 [ [3], [9,20], [1 ...

  7. 【JS学习】String基础方法

    前言:本博客系列为学习后盾人js教程过程中的记录与产出,如果对你有帮助,欢迎关注,点赞,分享.不足之处也欢迎指正,作者会积极思考与改正. 目录 定义: 字符串的连接: 标签模板的使用: 字符串的基本方 ...

  8. 鸿蒙的fetch请求加载聚合数据的前期准备工作-手动配置网络权限

    目录: 1.双击打开"config.json"文件 2.找到配置网络访问权限位置1 3.配置内容1 4.默认访问内容是空的 5.添加配置内容2 6.复制需要配置的网络二级URL 7 ...

  9. 删除开发账号的ACCESS KEY

    大家都知道,当申请一个开发账号来开发程序的时候需要一个ACCESS key,这个key我们可以通过系统管理员在OSS上注册, 也可以通过一些软件来计算,比如zapgui.EXE,但是当用软件注册完,不 ...

  10. Sentry(v20.12.1) K8S 云原生架构探索,JavaScript 性能监控之管理 Transactions

    系列 Sentry-Go SDK 中文实践指南 一起来刷 Sentry For Go 官方文档之 Enriching Events Snuba:Sentry 新的搜索基础设施(基于 ClickHous ...