当前位置: 代码网 > it编程>编程语言>Java > springboot对接poi实现导出excel并动态生成折线图

springboot对接poi实现导出excel并动态生成折线图

2025年10月09日 Java 我要评论
在spring boot项目中,使用apache poi库可以实现将数据导出为excel并嵌入动态生成的折线图。下面为您详细介绍具体的实现步骤、核心代码以及注意事项。环境准备:添加依赖首先,在您的po

在spring boot项目中,使用apache poi库可以实现将数据导出为excel并嵌入动态生成的折线图。下面为您详细介绍具体的实现步骤、核心代码以及注意事项。

环境准备:添加依赖

首先,在您的pom.xml文件中添加必要的依赖。推荐使用较新版本的poi以确保功能稳定。

<dependencies>
    <!-- spring boot web 支持 -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
    <!-- apache poi 核心库 -->
    <dependency>
        <groupid>org.apache.poi</groupid>
        <artifactid>poi</artifactid>
        <version>5.2.3</version>
    </dependency>
    <!-- 处理 xlsx 格式的ooxml支持 -->
    <dependency>
        <groupid>org.apache.poi</groupid>
        <artifactid>poi-ooxml</artifactid>
        <version>5.2.3</version>
    </dependency>
    <!-- 可选的模式支持,某些图表功能需要 -->
    <dependency>
        <groupid>org.apache.poi</groupid>
        <artifactid>poi-ooxml-schemas</artifactid>
        <version>4.1.2</version>
    </dependency>
</dependencies>

定义数据模型

为了清晰管理图表数据和在excel中的位置,建议先定义两个实体类。

​1. 折线图数据模型 (linechart):​​ 这个类用于封装折线图的所有元素,包括标题、数据系列和x轴标签。

@data
@accessors(chain = true)
public class linechart {
    /**
     * 图表的名称(主标题)
     */
    private string charttitle;
    /**
     * 每条折线的名称(图例)
     */
    private list<string> titlelist;
    /**
     * 每条折线对应的数据值
     */
    private list<list<double>> datalist;
    /**
     * x轴的数据点标签(如:月份、季度)
     */
    private list<object> xaxislist;
}

​2. 图表位置模型 (chartposition):​​ 这个类用于精确定义图表在excel工作表中的位置和大小。

@data
@accessors(chain = true)
public class chartposition {
    /** 图表左上角所在的列索引(从0开始) */
    private int col1;
    /** 图表左上角所在的行索引(从0开始) */
    private int row1;
    /** 图表右下角所在的列索引 */
    private int col2;
    /** 图表右下角所在的行索引 */
    private int row2;
    // 以下偏移量通常可设为0
    private int dx1 = 0;
    private int dy1 = 0;
    private int dx2 = 0;
    private int dy2 = 0;
}

核心工具类:创建折线图

这是最关键的步骤,我们将创建一个工具类chartutils,其中的createline方法负责在指定的excel工作表中绘制折线图。

import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.charts.*;
import org.apache.poi.xddf.usermodel.chart.*;

public class chartutils {
    
    public static void createline(xssfsheet sheet, chartposition chartposition, linechart linechart) {
        // 1. 获取数据
        list<object> xaxislist = linechart.getxaxislist();
        list<string> charttitlelist = linechart.gettitlelist();
        list<list<double>> chartdatalist = linechart.getdatalist();
        string charttitle = linechart.getcharttitle();

        // 2. 创建绘图对象和图表锚点
        xssfdrawing drawing = sheet.createdrawingpatriarch();
        xssfclientanchor anchor = drawing.createanchor(0, 0, 0, 0, 
                                                     chartposition.getcol1(), chartposition.getrow1(), 
                                                     chartposition.getcol2(), chartposition.getrow2());
        // 3. 创建图表并设置标题
        xssfchart chart = drawing.createchart(anchor);
        chart.settitletext(charttitle);
        chart.settitleoverlay(false);

        // 4. 设置图例位置
        xddfchartlegend legend = chart.getoraddlegend();
        legend.setposition(legendposition.top);

        // 5. 创建坐标轴
        xddfcategoryaxis bottomaxis = chart.createcategoryaxis(axisposition.bottom);
        xddfvalueaxis leftaxis = chart.createvalueaxis(axisposition.left);

        // 6. 准备数据源
        // 6.1 x轴数据(类别)
        xddfcategorydatasource countries = xddfdatasourcesfactory.fromarray(
                arrays.copyof(xaxislist.toarray(), xaxislist.size(), string[].class));
        // 6.2 创建折线图数据对象
        xddflinechartdata data = (xddflinechartdata) chart.createdata(charttypes.line, bottomaxis, leftaxis);

        // 7. 为每个数据系列创建折线
        for (int i = 0; i < chartdatalist.size(); i++) {
            list<double> values = chartdatalist.get(i);
            // 创建y轴数据源
            xddfnumericaldatasource<double> datasource = xddfdatasourcesfactory.fromarray(
                    values.toarray(new double[0]));
            
            // 将数据系列添加到图表
            xddflinechartdata.series series = (xddflinechartdata.series) data.addseries(countries, datasource);
            series.settitle(charttitlelist.get(i), null);
            series.setsmooth(false); // 设置为折线,非平滑曲线
            series.setmarkersize((short) 2); // 设置数据点标记的大小

            // (可选)特殊样式处理,例如为"警戒值"设置虚线
            if ("警戒值".equals(charttitlelist.get(i))) {
                xddflineproperties lineprops = new xddflineproperties();
                lineprops.setpresetdash(new xddfpresetlinedash(presetlinedash.dot));
                series.setlineproperties(lineprops);
            }
        }

        // 8. 绘制图表
        chart.plot(data);
    }
}

业务层整合与导出接口

最后,在spring boot的controller中,将数据导出和图表生成功能整合起来,提供一个http接口供前端调用。

@restcontroller
public class excelexportcontroller {

    @getmapping("/export/excel-with-chart")
    public void exportexcelwithchart(httpservletresponse response) throws ioexception {
        // 1. 设置响应头,告诉浏览器这是一个要下载的excel文件
        response.setcontenttype("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setheader("content-disposition", "attachment; filename="data_with_chart.xlsx"");
        
        // 2. 创建工作簿和工作表
        xssfworkbook workbook = new xssfworkbook();
        xssfsheet sheet = workbook.createsheet("数据报表");
        
        // 3. (可选)向工作表填充数据行...
        // 例如:createdatarows(sheet);
        
        // 4. 准备折线图数据
        linechart linechart = new linechart()
                .setcharttitle("销售趋势图")
                .setxaxislist(arrays.aslist("1月", "2月", "3月", "4月", "5月"))
                .settitlelist(arrays.aslist("产品a", "产品b", "警戒值"))
                .setdatalist(arrays.aslist(
                        arrays.aslist(120.0, 150.0, 180.0, 160.0, 200.0),
                        arrays.aslist(90.0, 120.0, 140.0, 130.0, 150.0),
                        arrays.aslist(150.0, 150.0, 150.0, 150.0, 150.0) // 警戒线
                ));
        
        // 5. 定义图表位置(例如:从第0行第0列开始,到第15行第10列结束)
        chartposition position = new chartposition()
                .setcol1(0).setrow1(10).setcol2(10).setrow2(25);
        
        // 6. 调用工具类创建折线图
        chartutils.createline(sheet, position, linechart);
        
        // 7. 将工作簿写入http响应流
        outputstream out = response.getoutputstream();
        workbook.write(out);
        workbook.close();
        out.flush();
    }
}

关键要点与优化建议

在实际使用中,请注意以下几点以确保最佳效果:

  • ​版本兼容性​​:确保所有poi相关依赖(如poi, poi-ooxml, poi-ooxml-schemas)的版本一致,以避免潜在的冲突。
  • ​图表位置规划​​:在插入图表前,最好先规划好数据表格的布局。chartposition中的行索引应考虑表格已占用的行数,防止图表覆盖数据。
  • ​大数据量优化​​:当需要导出的数据量非常大时,建议使用sxssfworkbook来代替xssfworkbook,它以流式处理方式工作,可以显著降低内存消耗。
  • ​前端调用​​:前端vue或react应用可以使用axios等库调用此导出接口,并通过处理返回的blob对象实现文件下载。

通过以上步骤,您就可以在spring boot应用中灵活地导出包含专业折线图的excel报表了。这套方法可以根据实际业务需求,轻松调整以生成柱状图或饼图等其他图表类型。

到此这篇关于springboot对接poi实现导出excel并动态生成折线图的文章就介绍到这了,更多相关springboot导出excel内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com