SpringBoot 数据导出excel

本文详细介绍如何在SpringBoot中实现Excel数据导出,包括使用Apache POI库、自定义视图解析器以及控制器实现。通过示例代码,读者可以快速掌握从依赖引入到具体业务场景的数据导出流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot导出数据的思路是自定义xls视图解析器

1、maven

<!-- Apache POI Microsoft Documents API -->
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>3.17</version>
</dependency>

2、自定义xls视图

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.StringUtil;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.view.document.AbstractXlsView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Spring Web - XLS视图
 */
public class ExcelView extends AbstractXlsView {

    /** 字符集 */
    private static final Charset UTF8 = StringUtil.UTF8;
    /** 文件名 */
    public static final String FILENAME_KEY = "filename";
    /** 属性 */
    public static final String PROPERTY_KEY = "properties";
    /** 内容 */
    public static final String CONTENT_KEY = "contents";

    @Override
    protected void buildExcelDocument(@SuppressWarnings("NullableProblems") Map<String, Object> model, @SuppressWarnings("NullableProblems") Workbook workbook, @SuppressWarnings("NullableProblems") HttpServletRequest request, @SuppressWarnings("NullableProblems") HttpServletResponse response) throws UnsupportedEncodingException {
        //获取文件名
        String filename = model.get(FILENAME_KEY) + "-" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ".xls";
        //获取属性
        LinkedHashMap<String, String> properties = (LinkedHashMap<String, String>) model.get(PROPERTY_KEY);
        //获取内容
        ArrayList<Map<String, Object>> contents = (ArrayList<Map<String, Object>>) model.get(CONTENT_KEY);
        // 标题样式-粗体
        CellStyle boldStyle = workbook.createCellStyle();
        Font fontStyle = workbook.createFont();
        fontStyle.setBold(true);
        boldStyle.setFont(fontStyle);
        // 写入excel
        Sheet sheet = workbook.createSheet();
        int rowNumber = 0;
        //写入标题
        if (MapUtils.isNotEmpty(properties)) {
            Row headerRow = sheet.createRow(rowNumber++);
            int cellNumber = 0;
            for (Map.Entry<String, String> property : properties.entrySet()) {
                Cell cell = headerRow.createCell(cellNumber++);
                cell.setCellStyle(boldStyle);
                cell.setCellValue(property != null ? property.getValue() : null);
                // 列宽自适应
                sheet.autoSizeColumn(cell.getColumnIndex(), true);
            }
        }
        // 写入内容
        if (CollectionUtils.isNotEmpty(contents)) {
            for (Map<String, Object> content : contents) {
                Row dataRow = sheet.createRow(rowNumber++);
                int cellNumber = 0;
                for (Map.Entry<String, String> property : properties.entrySet()) {
                    Cell cell = dataRow.createCell(cellNumber++);
                    cell.setCellValue(content != null && property != null ? String.valueOf(content.get(property.getKey())) : null);
                }
            }
        }
        //文件名编码
        String name;
        String userAgent = request.getHeader("user-agent").toLowerCase();
        if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
            // IE
            name = URLEncoder.encode(filename, UTF8.name());
        } else {
            // 非IE
            name = new String(filename.getBytes(UTF8.name()), "ISO-8859-1");
        }
        // 设置header 下载
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.builder("attachment").filename(name).build().toString());
        // 字符集
        response.setCharacterEncoding(UTF8.name());
    }
}

3、视图使用

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/export")
public class TestExportController {

    @GetMapping
    public ModelAndView exprot(){
        //属性
        Map<String, String> properties = new LinkedHashMap<>(4);
        properties.put("id", "ID");
        properties.put("name", "名称");
        properties.put("createDate", "创建时间");
        properties.put("updateDate", "更新时间");
        //内容
        List<Map<String, Object>> contents = new ArrayList<>();
        Map<String, Object> content = new HashMap<>(4);
        content.put("id", 1);
        content.put("name", "测试");
        content.put("createDate", new Date());
        content.put("updateDate", new Date());
        contents.add(content);
        //模型
        Map<String, Object> model = new HashMap<>(3);
        model.put(ExcelView.FILENAME_KEY, "测试数据导出");
        model.put(ExcelView.PROPERTY_KEY, properties);
        model.put(ExcelView.CONTENT_KEY, contents);
        //返回视图
        return new ModelAndView(new ExcelView(), model);
    }
}
### 如何在 SpringBoot 和 Vue 项目中实现导出 Excel 功能 #### 后端部分 (SpringBoot) 为了实现出 Excel 文件的功能,在后端可以使用 `EasyExcel` 或者传统的 `POI` 库来完成。以下是两种方式的具体实现: 1. **使用 EasyExcel** 易于配置和高性能的 `EasyExcel` 是一种流行的解决方案,尤其适用于大数据量场景。 - 添加依赖项到项目的 `pom.xml` 中: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>3.0.5</version> </dependency> ``` - 创建实体类用于映射 Excel 表格中的列: ```java import com.alibaba.excel.annotation.ExcelProperty; public class ExportStudentExcel { @ExcelProperty("学生姓名") private String name; @ExcelProperty("学号") private String studentNo; // Getter and Setter methods... } ``` - 编写服务方法以生成并返回 Excel 文件流: ```java import com.alibaba.excel.EasyExcel; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URLEncoder; import java.util.List; public void export(HttpServletResponse response, List<ExportStudentExcel> data) throws IOException { response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("utf-8"); String fileName = URLEncoder.encode("学生列表", "UTF-8").replaceAll("\\+", "%20"); response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx"); EasyExcel.write(response.getOutputStream(), ExportStudentExcel.class).sheet("模板").doWrite(data); } ``` 2. **使用 POI** 如果不想引入额外的第三方库,则可以选择 Apache POI 来手动创建 Excel 文档。 - 添加 Maven 依赖: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.3</version> </dependency> ``` - 使用以下代码片段编写控制器逻辑: ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; public void exportWithPoi(HttpServletResponse response, List<String[]> dataList) throws IOException { SXSSFWorkbook workbook = new SXSSFWorkbook(); Sheet sheet = workbook.createSheet("学生信息表"); Row rowHeader = sheet.createRow(0); CellStyle headerCellStyle = workbook.createCellStyle(); Font font = workbook.createFont(); font.setBold(true); headerCellStyle.setFont(font); String[] headers = {"序号", "姓名", "年龄"}; for(int i=0;i<headers.length;i++) { Cell cell = rowHeader.createCell(i); cell.setCellValue(headers[i]); cell.setCellStyle(headerCellStyle); } int rowNum = 1; for(String[] rowData : dataList){ Row row = sheet.createRow(rowNum++); for(int j=0;j<rowData.length;j++){ row.createCell(j).setCellValue(rowData[j]); } } ServletOutputStream outputStream = response.getOutputStream(); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition","attachment; filename=\"students.xlsx\""); workbook.write(outputStream); workbook.close(); outputStream.flush(); outputStream.close(); } ``` #### 前端部分 (Vue.js) 前端主要通过调用接口获取服务器生成好的文件链接或者二进制数据,并触发浏览器下载行为。 1. 定义 API 请求函数: ```javascript async function downloadFile() { const res = await axios({ method: 'GET', url: '/api/export/excel', // 替换为实际的服务地址 responseType: 'blob' }); let blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); let link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = 'student_list.xlsx'; // 设置默认保存名称 link.click(); } ``` 2. 调整按钮点击事件绑定上述方法即可。 --- ### 总结 无论是选用哪种技术方案,都需要考虑以下几个方面: - 数据源准备(数据库查询)。 - 文件格式定义以及样式定制化需求。 - 用户界面设计以便发起请求动作[^3]。 以上介绍了基于 Spring Boot 和 Vue 构建应用程序时如何集成 Excel 导出功能的一些基本概念和技术细节[^4]^。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值