Spring Boot 导出Excel表格
Spring Boot 导出Excel表格
添加支持
<!--添加导入/出表格依赖-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
新建Excel实体类
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;
}
}
添加excel工具类
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.OutputStream;
import java.util.List; import com.soft.ssmproject.entity.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 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; 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;
} private static int writeRowsToExcel(XSSFWorkbook wb, Sheet sheet, List<List<Object>> rows, int rowIndex) {
int colIndex = 0; 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;
} 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(BorderSide.TOP, color);
style.setBorderColor(BorderSide.LEFT, color);
style.setBorderColor(BorderSide.RIGHT, color);
style.setBorderColor(BorderSide.BOTTOM, color);
}
}
# controller层
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map; import javax.servlet.http.HttpServletResponse; import com.soft.ssmproject.entity.ExcelData;
import com.soft.ssmproject.entity.ExcelInfo;
import com.soft.ssmproject.tool.ExcelUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; @RestController
@RequestMapping("/excel")
public class ExcelController {
@RequestMapping(value = "/export", method = RequestMethod.POST)
public void excel(HttpServletResponse response,ExcelInfo excelInfo) throws Exception {
ExcelData data = new ExcelData();
data.setName("用户信息数据");
//添加表头
List<String> titles = new ArrayList();
//for(String title: excelInfo.getNames())
titles.add(excelInfo.getNames()[0]);
titles.add(excelInfo.getAccount()[0]);
titles.add(excelInfo.getDept()[0]);
titles.add(excelInfo.getGender()[0]);
titles.add(excelInfo.getEmail()[0]);
data.setTitles(titles);
//添加列
List<List<Object>> rows = new ArrayList();
List<Object> row = null;
for(int i=1; i<excelInfo.getNames().length;i++){
row=new ArrayList();
row.add(excelInfo.getNames()[i]);
row.add(excelInfo.getAccount()[i]);
row.add(excelInfo.getDept()[i]);
row.add(excelInfo.getGender()[i]);
row.add(excelInfo.getEmail()[i]);
rows.add(row); } data.setRows(rows); SimpleDateFormat fdate=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String fileName=fdate.format(new Date())+".xls";
ExcelUtils.exportExcel(response, fileName, data);
}
}
转子:https://blog.csdn.net/Cool_breeze_Rainy/article/details/80572308
Spring Boot 导出Excel表格的更多相关文章
- Spring boot 导出Excel
Html页面: window.location.href="adjectfkController/exportTemplate?adjOrg="+ adjOrg +"&a ...
- spring mvc项目中导出excel表格简单实现
查阅了一些资料,才整理出spring mvc 项目导出excel表格的实现,其实很是简单,小计一下,方便以后查阅,也希望帮助有需要的朋友. 1.导入所需要依赖(Jar包).我使用的是maven,所以坐 ...
- PHP导入导出excel表格图片(转)
写excel的时候,我用过pear的库,也用过pack压包的头,同样那些利用smarty等作的简单替换xml的也用过,csv的就更不用谈了.呵呵.(COM方式不讲了,这种可读的太多了,我也写过利用wp ...
- java中使用jxl导出Excel表格详细通用步骤
该方法一般接收两个参数,response和要导出的表格内容的list. 一般我们将数据库的数据查询出来在页面进行展示,根据用户需求,可能需要对页面数据进行导出. 此时只要将展示之前查询所得的数据放入s ...
- .NET环境下导出Excel表格的两种方式和导入两种类型的Excel表格
一.导出Excel表格的两种方式,其中两种方式指的是导出XML数据类型的Excel(即保存的时候可以只需要修改扩展名为.xls)和真正的Excel这两种. using System; using Sy ...
- java导出excel表格
java导出excel表格: 1.导入jar包 <dependency> <groupId>org.apache.poi</groupId> <artifac ...
- 使用NPOI将数据库里信息导出Excel表格并提示用户下载
使用NPOI进行导出Excel表格大家基本都会,我在网上却很少找到导出Excel表格并提示下载的 简单的代码如下 //mvc项目可以传多个id以逗号相隔的字符串 public ActionResult ...
- VB.NET版机房收费系统---导出Excel表格
datagridview,翻译成中文的意思是数据表格显示,使用DataGridView控件,能够显示和编辑来自不同类型的数据源的表格,将数据绑定到DataGridView控件很easy和直观,大多数情 ...
- C#导出Excel表格方法
using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using NPOI.SS.Formula.Functions; using System.Re ...
随机推荐
- 修改/dev/shm大小 tmps
/dev/shm 在oracle开启AMM时发现/dev/shm下的空间不够用 WARNING: You are trying to use the MEMORY_TARGET feature. T ...
- 前段基础之CSS
本文参考:https://www.cnblogs.com/ctztake/p/7577436.html CSS 语法 CSS规则由两个主要的部分构成:选择器,以及一条或多条声明. ''' select ...
- make 命令【转】
转自:https://www.ibm.com/support/knowledgecenter/zh/ssw_aix_71/com.ibm.aix.cmds3/make.htm#make__row-d3 ...
- C++学习day1
1. 有符号整数 对于有符号整数,最高位为0表示正数,为1表示负数 负数的绝对值为除最高位外,其余取反再加1 int 字节数:4,取值范围:-232~232-1 最大值为232-1 最小值即为 000 ...
- win10 python27pyhton36共存
先前安装了python36 然后安装python27,安装步骤如下 1. 到官网下载https://www.python.org/downloads/windows/,我的是win10 64位,选择了 ...
- 转-JavaWeb三大组件之Listener监听器
JavaWeb三大组件之Listener监听器一.概述1,它是一个接口,内容由我们来实现 2,它需要注册,例如注册在按钮上 3,监听器中的方法,会在特殊事件发生时被调用 二.JavaWeb中的监听器1 ...
- python迭代器的说明
data = [randint(0,20) for _ in xrange(30)]表示30个随机生成的0-20随机数其中for _ in xrange(30)表示循环30次. from random ...
- $Djangon admin界面 添加表 增删查改
from django.contrib import admin表变中文 class Meta: verbose_name_plural='评论表' null=True的字段:admin创建要求写可以 ...
- UVA 1395 MST
给你一个图, 求一个生成树, 边权Max – Min 要最小,输出最小值, 不能构成生成树的 输出 -1: 思路: Keuksal 算法, 先排序边, 然后枚举 第一条边, 往后加入边, 直到有 n- ...
- 【原创】大叔经验分享(38)beeline连接hiveserver2报错impersonate
beeline连接hiveserver2报错 Error: Could not open client transport with JDBC Uri: jdbc:hive2://localhost: ...