SpringBoot导出Excel表格
程序员文章站
2024-01-03 21:42:58
...
0、先在pom.xml里面添加POI依赖,Java轻熟鸟从第六步看
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8</version>
</dependency>
1、编写mapper.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hotcomm.prevention.db.mysql.datashow.dc.DcMapper">
<select id="selectDeviceList" resultType="import你的查询结果的实体类路径">
SELECT
dc.*
FROM
t_device_all dc
INNER JOIN
t_device_group_relation t1
ON t1.`deviceid` = dc.`id`
AND t1.`isdelete`
= 0
INNER JOIN t_device_group t2
ON t1.`groupid` = t2.`id`
AND
t2.`isdelete` = 0
INNER JOIN t_user_dgroup_relation t3
ON
t3.`devicegroupid` = t2.`id`
AND t3.`isdelete` = 0
INNER JOIN t_user t4
ON t4.`id` = t3.`userid`
AND t4.`isdelete` = 0
AND t4.`id` =#{userid}
</select>
</mapper>
2、写一个存放单表查询结果的实体类(lombok可以自动编译getter和setter,此处省略lombok的配置安装,如需使用请百度)
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
@Table(name = "t_device_all ")
@Data
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
public class T_device_all implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "devnum")
private String devnum;
@Column(name = "mac")
private String mac;
}
3、编辑你的毛片儿(mapper.java)
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface DcMapper{
List<T_device_all> selectDeviceList(@Param("userid") Integer userid);
}
4、编辑service
import java.text.ParseException;
import java.util.List;
public interface DcService {
List<T_device_all> selectDevice(Integer userid);
}
5、接着是serviceImpl(SpringBoot、SSM是真的优雅)
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
@Service
public class DcServiceImpl implements DcService {
@Autowired
private DcMapper dcMapper;
@Override
public List<T_device_all> selectDevice(Integer userid) {
return dcMapper.selectDeviceList(userid);
}
}
6、编写Excel模板实体类
import java.io.Serializable;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
@Data
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
public class ExcelData implements Serializable {
private static final long serialVersionUID = 1L;
// 表头
private List<String> titles;
// 数据
private List<List<Object>> rows;
// 页签名称
private String name;
}
7、编写Excel工具类(设置你要导出的Excel表格样式,基本不需要修改)
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;
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 ExcelOutPutUtils {
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);
}
}
8、配置controller
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
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 ExcelOutPutController {
@Autowired
DcService dcService;
@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("设备编号");
titles.add("mac地址");
data.setTitles(titles);
List<List<Object>> rows = new ArrayList();
List<T_device_all> list = dcService.selectDevice(1);//sql查询结果放在这个数组里
for (int i = 0; i < list.size(); i++) {//遍历数组,把数组内容放进Excel的行中
List<Object> row = new ArrayList();
row.add(list.get(i).getDevnum());
row.add(list.get(i).getMac());
rows.add(i, row);
}
data.setRows(rows);
//生成本地
/*File f = new File("c:/test.xlsx");
FileOutputStream out = new FileOutputStream(f);
ExportExcelUtils.exportExcel(data, out);
out.close();*/
SimpleDateFormat fdate=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String fileName=fdate.format(new Date())+".xlsx";//老版本的office改成xls
ExcelOutPutUtils.exportExcel(response,fileName,data);
}
}
最后启动项目,在浏览器中测试
http://localhost:8081/excel/export?userid=1(端口、拦截路基、传参 是自定义的)
输入地址后敲回车,下载成功了
结果吻合查询结果,导出完成