1. Introduce poi dependency in pom.xml
<!-- POI EXCEL 文件读写 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-excelant</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.1.2</version>
</dependency>
2. Write a tool class for exporting excel files
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class ExportExcel {
// 导出表的标题
private String title;
// 导出表的列名
private String[] rowName;
// 导出表的数据
private List<Object[]> dataList = new ArrayList<Object[]>();
// 构造函数,传入要导出的数据
public ExportExcel(String title, String[] rowName, List<Object[]> dataList) {
this.dataList = dataList;
this.rowName = rowName;
this.title = title;
}
// 导出数据
public void export(OutputStream out) throws Exception {
try {
//1.创建一个workbook,一个workbook 对应一个Excel文件
HSSFWorkbook workbook = new HSSFWorkbook();
//2.创建 sheet excel中多个sheet组成一个excel文件 至少有一个sheet
HSSFSheet sheet = workbook.createSheet(title);
//3.在sheet中添加表头第0行
HSSFRow rowm = sheet.createRow(0);
//4.创建单元格
HSSFCell cellTitle = rowm.createCell(0);
//5.定义标题样式 和 数据样式
HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);
HSSFCellStyle style = this.getStyle(workbook);
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length - 1)));
cellTitle.setCellStyle(columnTopStyle);
//6.给单元格设置值
cellTitle.setCellValue(title);
//7.获取列标长度
int columnNum = rowName.length;
// 创建列 相当于一行 2代表第三行 因为上面的总标题占了两行为 0 1
HSSFRow rowRowName = sheet.createRow(2);
//8.将列标题设置到单元格中
for (int n = 0; n < columnNum; n++) {
HSSFCell cellRowName = rowRowName.createCell(n);
cellRowName.setCellType(CellType.STRING);
HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
cellRowName.setCellValue(text);
cellRowName.setCellStyle(style);
}
//9.将数据设置到单元格中
for (int i = 0; i < dataList.size(); i++) {
Object[] obj = dataList.get(i);
HSSFRow row = sheet.createRow(i + 3);
for (int j = 0; j < obj.length; j++) {
HSSFCell cell = null;
cell = row.createCell(j, CellType.STRING);
if (!"".equals(obj[j]) && obj[j] != null) {
cell.setCellValue(obj[j].toString());
} else {
cell.setCellValue(" ");
}
cell.setCellStyle(style);
}
}
if (workbook != null) {
try {
//10.将整个表格写出
workbook.write(out);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) { }
}
/**
* 表格标题样式
*/
public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
// 设置字体
HSSFFont font = workbook.createFont();
// 设置字体大小
font.setFontHeightInPoints((short) 11);
// 设置字体颜色
font.setColor(IndexedColors.WHITE.getIndex());
// 字体加粗
font.setBold(true);
// 设置字体名字
font.setFontName("Courier New");
// 设置样式
HSSFCellStyle style = workbook.createCellStyle();
// 设置标题背景色
style.setFillForegroundColor(IndexedColors.DARK_TEAL.getIndex());
// 设置背景颜色填充样式
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 设置低边框
style.setBorderBottom(BorderStyle.THIN);
// 设置低边框颜色
style.setBottomBorderColor(IndexedColors.ROYAL_BLUE.getIndex());
// 设置右边框
style.setBorderRight(BorderStyle.THIN);
// 设置顶边框
style.setTopBorderColor(IndexedColors.ROYAL_BLUE.getIndex());
// 设置顶边框颜色
style.setTopBorderColor(IndexedColors.ROYAL_BLUE.getIndex());
// 在样式中应用设置的字体
style.setFont(font);
// 设置自动换行
style.setWrapText(false);
// 设置水平对齐的样式为居中对齐;
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
/**
* 表格数据样式
*/
public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
// 设置字体
HSSFFont font = workbook.createFont();
// 设置字体大小
font.setFontHeightInPoints((short) 10);
// 设置字体名字
font.setFontName("Courier New");
// 设置样式;
HSSFCellStyle style = workbook.createCellStyle();
// 设置底边框;
style.setBorderBottom(BorderStyle.THIN);
// 设置底边框颜色;
style.setBottomBorderColor(IndexedColors.ROYAL_BLUE.getIndex());
// 设置左边框;
style.setBorderLeft(BorderStyle.THIN);
// 设置左边框颜色;
style.setLeftBorderColor(IndexedColors.ROYAL_BLUE.getIndex());
// 设置右边框;
style.setBorderRight(BorderStyle.THIN);
// 设置右边框颜色;
style.setRightBorderColor(IndexedColors.ROYAL_BLUE.getIndex());
// 设置顶边框;
style.setBorderTop(BorderStyle.THIN);
// 设置顶边框颜色;
style.setTopBorderColor(IndexedColors.ROYAL_BLUE.getIndex());
// 在样式用应用设置的字体;
style.setFont(font);
// 设置自动换行;
style.setWrapText(false);
// 设置水平对齐的样式为居中对齐;
style.setAlignment(HorizontalAlignment.CENTER);
// 设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
}
3. Add an export method in the service layer
void exportExcel(OutputStream out, String excelTitle) throws IOException;
4. Write specific and database implementation functions in Ipml
The specific details can be modified according to your needs.
/**
* 导出数据为excel
*/
@Override
public void exportExcel(OutputStream out, String excelTitle) throws IOException {
// 定义列标 就是一个Excel的每一个字段标题
String[] rowsName = new String[]{"订单id", "用户", "订单号", "产品名称", "价格/¥", "订单状态", "更新时间"};
// 创建导出数据集合 后续会将dataList中的数据写到Excel
List<Object[]> dataList = new ArrayList<>();
// 从数据库查询用户列表(需要的可以自行添加参数)
QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
List<Order> orderList = orderMapper.selectList(queryWrapper);
Order order = null;
// 将列表信息封装到一个Object数组
// 我这里封装Object数组 是为了方便后续代码复用,不会将对象类型写死
for (int i=0; i<orderList.size(); i++){
//将数据库查到的每条数据 循环封装到Object[]
order=orderList.get(i);
order.setUserName(userMapper.selectById(order.getUserId()).getName());
Object[] objs = new Object[]{order.getId(),order.getUserName(),order.getOrderNo(),order.getTitle(),order.getTotalFee(),order.getOrderStatus(),order.getUpdateTime()};
//将转换好的数据 存入dataList
dataList.add(objs);
}
// 创建ExportExcel工具类对象 通过构造方法赋值
ExportExcel ex = new ExportExcel(excelTitle, rowsName, dataList);
try {
// 调用生成Excel的方法,将数据通过输出流写出
ex.export(out);
} catch (Exception e) {
e.printStackTrace();
}
out.flush();
out.close();
}
5. Write the response code of the get request at the controller layer
@GetMapping("/exportExcel/{excelTitle}")
public Object exportExcel(HttpServletResponse response, @PathVariable String excelTitle) throws IOException {
log.info("下载订单为excel表...");
// 创建导出文件名称 当前日期+前台传递过来的标题名(excelTitle)
String fileName = DateUtils.format(new Date(),"yyyyMMddHHmmss") +"-"+excelTitle+".xls";
// 设置返回的消息头和返回值类型 并设置编码 不设置编码文件名为中文的话 不会显示
// 当设置成如下返回值时,浏览器才会执行下载文件动作
response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");
// 创建输出流,调用service中exportTest方法,参数:输出流 标题名
orderService.exportExcel(response.getOutputStream(), excelTitle);
return null;
}
6. Front-end call interface code
<el-button @click="exportExcel">
<i class="el-icon-download"></i>下载所有订单信息
</el-button>
methods: {
// 下载订单
exportExcel() {
// 这里可以传入一些查询参数,我在这里传入了标题内容
// 将标题内容作为导出的Excel文件名,此处的标题内容后期可动态改变
let url = 'http://localhost:8051/api/order/exportExcel/订单信息'
window.open(url)
}
}