注意:由于公司需要大量导出数据成excel表格,因此在网上找了方法,亲测有效.

声明:该博客参考于https://blog.csdn.net/long530439142/article/details/79002792,谢谢哥们提供方法。

1、在pom.xml中添加poi-ooxml组件

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

2、excel自定义数据格式

package com.cn.commodity.dto;

import java.io.Serializable;
import java.util.List; public class ExcelData implements Serializable {
private static final long serialVersionUID = 4444017239100620999L; // 表头
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、ExcelUtils 工具类

package com.cn.commodity.utils;
import com.cn.commodity.dto.ExcelData;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;
import java.awt.Color;
import java.net.URLEncoder; public class ExcelUtils {
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, "utf-8"));
exportExcel(data, response.getOutputStream());
} public static void exportExcel(ExcelData data, OutputStream out) throws Exception { XSSFWorkbook wb = new XSSFWorkbook();
try {
String sheetName = data.getName();
if (null == sheetName) {
sheetName = "Sheet1";
}
XSSFSheet sheet = wb.createSheet(sheetName);
writeExcel(wb, sheet, data); wb.write(out);
} catch(Exception e){
e.printStackTrace();
}finally{
//此处需要关闭 wb 变量
out.close();
}
} private static void writeExcel(XSSFWorkbook wb, Sheet sheet, ExcelData data) { int rowIndex = 0; rowIndex = writeTitlesToExcel(wb, sheet, data.getTitles());
writeRowsToExcel(wb, sheet, data.getRows(), rowIndex);
autoSizeColumns(sheet, data.getTitles().size() + 1); } private static int writeTitlesToExcel(XSSFWorkbook wb, Sheet sheet, List<String> titles) {
int rowIndex = 0;
int colIndex = 0; XSSFFont titleFont = wb.createFont();
titleFont.setFontName("simsun");
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);
colIndex = 0; for (String field : titles) {
Cell cell = titleRow.createCell(colIndex);
cell.setCellValue(field);
cell.setCellStyle(titleStyle);
colIndex++;
} rowIndex++;
return rowIndex;
} private static int writeRowsToExcel(XSSFWorkbook wb, Sheet sheet, List<List<Object>> rows, int rowIndex) {
int colIndex = 0;
XSSFFont dataFont = wb.createFont();
dataFont.setFontName("simsun");
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);
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;
} 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);
}
}
} private static void setBorder(XSSFCellStyle style, BorderStyle border, XSSFColor color) {
style.setBorderTop(border);
style.setBorderLeft(border);
style.setBorderRight(border);
style.setBorderBottom(border);
style.setBorderColor(XSSFCellBorder.BorderSide.TOP, color);
style.setBorderColor(XSSFCellBorder.BorderSide.LEFT, color);
style.setBorderColor(XSSFCellBorder.BorderSide.RIGHT, color);
style.setBorderColor(XSSFCellBorder.BorderSide.BOTTOM, color);
}
}

4、写一个Controller,在本地生成文件

package com.cn.commodity.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; import javax.servlet.http.HttpServletResponse; import com.cn.commodity.dto.ExcelData;
import com.cn.commodity.utils.ExcelUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; @RestController
@RequestMapping("/excel")
public class ExcelController {
@RequestMapping(value = "/export", method = RequestMethod.GET)
public void excel(HttpServletResponse response) throws Exception {
ExcelData data = new ExcelData();
data.setName("hello");
List<String> titles = new ArrayList();
titles.add("a1");
titles.add("a2");
titles.add("a3");
data.setTitles(titles); List<List<Object>> rows = new ArrayList();
List<Object> row = new ArrayList();
row.add("11111111111");
row.add("22222222222");
row.add("3333333333");
rows.add(row); data.setRows(rows); //生成本地
File f = new File("F:\\test.xlsx");
FileOutputStream out = new FileOutputStream(f);
ExcelUtils.exportExcel(data, out);
out.close();
/* SimpleDateFormat fdate=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String fileName=fdate.format(new Date())+".xls";
ExcelUtils.exportExcel(response,fileName,data);*/
}
}

本人实测有效,如有问题,欢迎留言!

springboot2.0数据制作为excel表格的更多相关文章

  1. Java POI读取Excel数据,将数据写入到Excel表格

    1.准备 首先需要导入poi相应的jar包,包括: 下载地址:http://pan.baidu.com/s/1bpoxdz5 所需要的包的所在位置包括: 2.读取Excel数据代码 package S ...

  2. 把数据库中的数据制作成Excel数据

    把数据库中的数据制作成Excel数据 如果我们在使用Excel的时候,需要把数据库中的数据制作成Excel数据透视表,我们该怎么操作呢?如果数据在数据库中,我们不用把数据导入到工作表中,我们可以直接以 ...

  3. asp.net数据导出到excel表格,并设置表格样式

    1.首先在项目中添加引用

  4. 从数据库将数据导出到excel表格

    public class JxlExcel { public static void main(String[] args) { //创建Excel文件 String[] title= {" ...

  5. 数据导出为excel表格

    ---恢复内容开始--- 方式一: 通过request和response中携带的数据导出表格,导出的结果会将页面中展示的内容全部导出.代码如下: //调出保存框,下载页面所有内容 String fil ...

  6. poi实现将数据输出到Excel表格当中

    今天简单的学习了一下POI,一下是所使用到的jar,这些jar可以到apache去下载

  7. java将数据库中查询到的数据导入到Excel表格

    1.Maven需要的依赖 <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> ...

  8. 将数据库中数据导出为excel表格

    public class Excel { private static Logger logger = LoggerFactory.getLogger(Excel.class); /** * 导出项目 ...

  9. 非常简单的数据,支持excel表格下载功能

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"% ...

随机推荐

  1. 第十三章·Kibana深入-使用地图统计客户端IP

    地址库 在ELK中,我们可以使用地址库,来对IP进行分析,对日志进行分析,在ELKstack中只有Logstash可以做到,但是出图,是Kibana来出的,所以我们首先需要下载地址库数据文件,然后对L ...

  2. [微信小程序]聊天对话(文本,图片)的功能(完整代码附效果图)

    废话不多说, 先上图: <!--pages/index/to_news/to_news.wxml--> <view class='tab'> <view class='l ...

  3. GitHub 上最热的10款国产开源软件

    衡量一个开源产品好不好,看看产品在 GitHub 的 Star 数量就知道了.由此可见,GitHub 已经沦落为开源产品的“大众点评”了.一个开源产品希望快速的被开发者知道.快速的获取反馈,放到 Gi ...

  4. mybatis整合Spring编码

    mybatis整合Spring的核心代码 spring-dao.xml <?xml version="1.0" encoding="UTF-8"?> ...

  5. 记一次Python导包经历

    最近由于需要写一个脚本调用另一个文件里面的一个方法,试了很久都导包失败,特此记录一下 问题背景 1)脚本文件为send_reward.py,要调用public_model_func.py里面的一个类方 ...

  6. postman 跟restsharp 模拟请求http

    https://github.com/restsharp/RestSharp postman 生成的访问代码: 好用! Features Assemblies for .NET 4.5.2 and . ...

  7. bzoj3307 雨天的尾巴题解及改题过程(线段树合并+lca+树上差分)

    题目描述 N个点,形成一个树状结构.有M次发放,每次选择两个点x,y对于x到y的路径上(含x,y)每个点发一袋Z类型的物品.完成所有发放后,每个点存放最多的是哪种物品. 输入格式 第一行数字N,M接下 ...

  8. 『HGOI 20190917』Lefkaritika 题解 (DP)

    题目概述 一个$n \times m$的整点集.其中$q$个点被m被设置为不能访问. 问这个点集中含有多少个不同的正方形,满足不包含任何一个不能访问的点. 对于$50\%$的数据满足$1 \leq n ...

  9. interp2

    %关于interp2的自我理解 %利用已知的信息,对数据进行拟合 %用一个例子进行理解 例:设有数据x=1,2,3,4,5,6,y=1,2,3,4,在由x,y构成的网格上,数据为:12,10,11,1 ...

  10. .py文件打包成.exe文件

    # 使用pyinstaller模块 # pip install pyinstaller # 在命令行执行 pyinstaller -F xxx.py