Vue+SpringBoot使用POI导出EXCEL



前言

随着数据报表的重要性以及大部分项目的需要,然后就在这里简单做了一篇使用poi完成excel导出并且在浏览器上的下载。可以使用谷歌Browser秒秒钟完成下载,然后打开即可看到导出的数据

一、VUE前端

前端:因为项目使用了前后端分离,所以在前端只是简单调用后端的接口,并传入一些可有可无的参数。数据的查询以及导出业务代码基本都是在后端

1.请求部分

一个按钮,一个方法即可
代码如下:

<div class="pd-md">
      <mt-button @click="exportTest" plain size="large">导  出</mt-button>
</div>
methods: {
 exportTest(){
 	// 这里可以传入一些查询参数,我在这里传入了标题内容
    var url = 'http://localhost:8089/api/reportExport/prodTest?excelTitle='+ this.searchData.excelTitle
    window.open(url)
  }
},


二、SpringBoot后端

1.POI依赖引入

代码如下:

<!-- POI EXCEL 文件读写 -->
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-excelant -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-excelant</artifactId>
    <version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>4.1.2</version>
</dependency>

2.控制层

这里简单规定文件名称,调用service接口方法即可
Controller代码如下:

@GetMapping("/reportExport/prodTest")
@ApiOperation(value="测试导出" , notes ="测试导出" ,  response = Result.class)
@ApiImplicitParams({
        @ApiImplicitParam(name = "参数1", value = "excelTitle", dataType = "string", paramType = "query")
})
public Object prodTest(HttpServletResponse response, String excelTitle) throws IOException {
    String fileName = DateUtils.format(new Date(),"yyyyMMddHHmmss") +"-STU.xls";
    String headStr = "attachment; filename=" + fileName;
    response.setContentType("APPLICATION/OCTET-STREAM");
    response.setHeader("Content-Disposition", headStr);
    reportService.exportTest(response.getOutputStream(), excelTitle);
    return null;
}

3.业务逻辑

定义导出测试接口方法
ReportService接口代码如下:

public interface ReportService {

	void exportTest(OutputStream out, String excelTitle) throws IOException;
	
}

定义Service实现类,这里可以根据参数查询数据,并设置列头,封装数据集合调用导出工具类中的方法
ReportServiceImpl代码如下:

@Service
public class ReportServiceImpl implements ReportService {

    @Override
    public void exportTest(OutputStream out, String excelTitle) throws IOException {

        // 定義列頭
        String[] rowsName = new String[]{"序号", "用户名", "密码", "是否禁用"};
        List<Object[]> dataList = new ArrayList<Object[]>();

		// 模拟数据
        List<Map<String,Object>> list  = new ArrayList<>();

        Map<String,Object> map = new HashMap<>();
        map.put("userAccount", "zs");
        map.put("userPwd", "123");
        map.put("userDelete", true);

        Map<String,Object> map2 = new HashMap<>();
        map2.put("userAccount", "lisi");
        map2.put("userPwd", "111");
        map2.put("userDelete", false);

        list.add(map);
        list.add(map2);

        // 存入數據
        for (Map<String,Object> m : list) {
            Object[] objs = new Object[]{"", m.get("userAccount"), m.get("userPwd"),
                    (boolean)m.get("userDelete") ? "已删除":"启用中"};
            dataList.add(objs);
        }

        // 生成EXCEL
        ExportExcel ex = new ExportExcel(excelTitle, rowsName, dataList);
        try {
            ex.export(out);
        } catch (Exception e) {
            e.printStackTrace();
        }
        out.flush();
        out.close();
    }

}

4.导出工具类

工具类中,定义样式,设值方法
ExportExcelUtil代码如下:

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 {
            // 創建一個EXCEL並設置名稱
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet(title);

            // 產生表格標題行
            HSSFRow rowm = sheet.createRow(0);
            HSSFCell cellTitle = rowm.createCell(0);

            // SHEET樣式定義
            HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);
            HSSFCellStyle style = this.getStyle(workbook);
            sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length - 1)));
            cellTitle.setCellStyle(columnTopStyle);
            cellTitle.setCellValue(title);

            // 定義所需要的列數
            int columnNum = rowName.length;
            HSSFRow rowRowName = sheet.createRow(2);

            // 將列頭設置到SHEET的單元格中
            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);
            }

            // 將數據設置到SHEET的單元格中
            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;
                    if (j == 0) {
                        cell = row.createCell(j, CellType.NUMERIC);
                        cell.setCellValue(i + 1);
                    } else {
                        cell = row.createCell(j, CellType.STRING);
                        if (!"".equals(obj[j]) && obj[j] != null) {
                            cell.setCellValue(obj[j].toString());
                        } else {
                            cell.setCellValue(" ");
                        }
                    }
                    cell.setCellStyle(style);
                }
            }

            // 讓列寬隨著導出的列長自動適應
            for (int colNum = 0; colNum < columnNum; colNum++) {
                int columnWidth = sheet.getColumnWidth(colNum) / 256;
                for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                    HSSFRow currentRow;
                    if (sheet.getRow(rowNum) == null) {
                        currentRow = sheet.createRow(rowNum);
                    } else {
                        currentRow = sheet.getRow(rowNum);
                    }
                    if (currentRow.getCell(colNum) != null) {
                        HSSFCell currentCell = currentRow.getCell(colNum);
                        if (currentCell.getCellType() == CellType.STRING) {
                            int length = currentCell.getStringCellValue().getBytes().length;
                            if (columnWidth < length) {
                                columnWidth = length;
                            }
                        }
                    }
                }
                if (colNum == 0) {
                    sheet.setColumnWidth(colNum, (columnWidth - 2) * 256);
                } else {
                    sheet.setColumnWidth(colNum, (columnWidth + 4) * 256);
                }
            }
            if (workbook != null) {
                try {
                    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;
    }
}

GAME OVER ! ! !



三、结果

看啊:

在这里插入图片描述


当然你想修改表格颜色方面的样式,也可以看下面几个博主的文章:

POI 4.12 版本颜色代码

POI 4.12 背景颜色模式

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现Vue和Spring Boot的Excel导出功能,可以按照以下步骤进行: 1. 在Vue中编写前端页面,包括按钮和表格等元素。 2. 在Vue中编写调用Spring Boot后端接口的函数,将需要导出的数据传递给后端。 3. 在Spring Boot中编写后端接口,接收前端传递的数据,并使用Apache POI库生成Excel文件。 4. 将生成的Excel文件返回给前端。 下面是一个简单的示例代码: Vue前端代码: ```html <template> <div> <el-button @click="exportExcel">导出Excel</el-button> <el-table :data="tableData" border> <el-table-column prop="name" label="姓名"></el-table-column> <el-table-column prop="age" label="年龄"></el-table-column> </el-table> </div> </template> <script> import axios from 'axios' export default { data() { return { tableData: [ { name: '张三', age: 18 }, { name: '李四', age: 20 }, { name: '王五', age: 22 } ] } }, methods: { exportExcel() { axios.post('/api/exportExcel', this.tableData).then(response => { const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' }) const downloadElement = document.createElement('a') const href = window.URL.createObjectURL(blob) downloadElement.href = href downloadElement.download = 'data.xlsx' document.body.appendChild(downloadElement) downloadElement.click() document.body.removeChild(downloadElement) window.URL.revokeObjectURL(href) }) } } } </script> ``` Spring Boot后端代码: ```java @RestController @RequestMapping("/api") public class ExcelController { @PostMapping("/exportExcel") public ResponseEntity<byte[]> exportExcel(@RequestBody List<Map<String, Object>> dataList) throws IOException { // 创建Excel文件 Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); Row headerRow = sheet.createRow(0); headerRow.createCell(0).setCellValue("姓名"); headerRow.createCell(1).setCellValue("年龄"); for (int i = 0; i < dataList.size(); i++) { Map<String, Object> data = dataList.get(i); Row dataRow = sheet.createRow(i + 1); dataRow.createCell(0).setCellValue((String) data.get("name")); dataRow.createCell(1).setCellValue((Integer) data.get("age")); } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); workbook.write(outputStream); return ResponseEntity.ok().contentType(MediaType.parseMediaType("application/vnd.ms-excel")) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + "data.xlsx" + "\"") .body(outputStream.toByteArray()); } } ``` 在这个示例中,我们使用了axios库来发送POST请求,将需要导出的数据传递给后端。后端接收到数据后,使用Apache POI库生成Excel文件,并将文件以字节数组的形式返回给前端。前端通过创建一个<a>元素,并设置其href属性为Excel文件的URL,来实现文件下载功能。 需要注意的是,这个示例中使用的是xlsx格式的Excel文件,如果需要生成xls格式的文件,可以将XSSFWorkbook改为HSSFWorkbook,同时将响应头的Content-Type改为"application/vnd.ms-excel"。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值