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
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值