Vue+SpringBoot使用POI导出EXCEL

news/2024/7/21 6:59:16 标签: java, vue.js, poi, excel

文章目录

  • 前言
  • 一、VUE前端
    • 1.请求部分
  • 二、SpringBoot后端
    • 1.POI依赖引入
    • 2.控制层
    • 3.业务逻辑
    • 4.导出工具类
  • 三、结果



前言

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

一、VUE前端

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

1.请求部分

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

javascript"><div class="pd-md">
      <mt-button @click="exportTest" plain size="large">导  出</mt-button>
</div>
javascript">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代码如下:

java">@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接口代码如下:

java">public interface ReportService {

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

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

java">@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代码如下:

java">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 背景颜色模式


http://www.niftyadmin.cn/n/856907.html

相关文章

VUE+Echarts调用天气API显示近日天气情况

VUEEcharts显示天气一、引入依赖1.npm安装2.Echarts的模板二、操作页面1.引用Echars.vue2.具体方法3.数据渲染4.调用api总结一、引入依赖 在这里你可以使用很多前端框架调用echarts&#xff0c;我的项目是vue端app程序&#xff0c;所以在这里就用vue方式引入echarts 1.npm安装…

怎么检测mysql查询是否慢_MySql慢查询语句检测方法

一、MySQL数据库有几个配置选项可以帮助我们及时捕获低效SQL语句1&#xff0c;slow_query_log这个参数设置为ON&#xff0c;可以捕获执行时间超过一定数值的SQL语句。2&#xff0c;long_query_time当SQL语句执行时间超过此数值时&#xff0c;就会被记录到日志中&#xff0c;建议…

使用POI读取EXCEL模板并填充数据,上传至腾讯云储存桶

读取EXCEL模板&#xff0c;并填充数据生成文件前言一、POI导入二、具体实现1.制作我们的模板2.读取模板来生成新的EXCEL3.查看生成结果三&#xff0c;传到腾讯云储存桶里1.导入COS依赖2.写个工具类3.调用代码上传并读取四&#xff0c;生成自定义XLSX模板1.主要代码2.结果3.注意…

java查询oracle数据库_Java连接Oracle数据库并查询

下载ODBC Jar包驱动,网上百度下载或者去官网下载&#xff0c;导入到Eclipse 项目里面建立连接public class DbConn {private static String driver "oracle.jdbc.driver.OracleDriver";private static String url "jdbc:oracle:thin:localhost:1521:orcl"…

Vue读取Excel文件转换为Html预览,打印

Vue读取网络路径Excel文件转换为Html预览&#xff0c;打印前言一、预览EXCEL文件1.获取网络路径Excel文件2.转换格式后的数据3.最终结果二、打印文件前言 我们需要对一些Excel文件进行预览&#xff0c;那么可以调用第三方的接口转到别的页面进行预览&#xff0c;可是这样比较花…

使用Hexo搭建博客并部署到服务器,告别访问延迟的烦恼

使用Hexo搭建个人博客&#xff0c;然后把代码提交到服务器&#xff0c;访问会很快哦前言一、安装所需环境1.Node.js安装2.Nginx安装二、使用Hexo搭建博客1.搭建一个新项目2.代码提交到服务器总结前言 一般我们的hexo个人博客都是放在github的&#xff0c;但毕竟是国外的东西&a…

java从小到大排序函数_Java8函数之旅 (五) -- Java8中的排序

前言对数据进行排序是平常经常会用到的操作之一&#xff0c;使用Jav8排序可以减少你在排序这方面的代码量&#xff0c;优化你的代码。测试用例代码定义个实体类User&#xff0c;拥有姓名name,年龄age,积分credits三个属性,定义一个包含User的集合&#xff0c;用于排序&#xff…

cucumber java 搭建_intelj idea cucumber java搭建教程

intel j idea cucumber java搭建教程Cucumber 是一个能够理解用普通语言 描述的测试用例的支持行为驱动开发(BDD)的自动化测试工具&#xff0c;用Ruby编写&#xff0c;支持Java和.Net等多种开发语言。cucumber是非常重要的&#xff0c;那么如何在java中正确使用cucumber呢&…