本文介绍如何根据现有excel数据在powerpoint中创建图表。该方案需引用spire.office.jar,请下载最新版本并在您的项目中添加为依赖。
excel文档截图:
import com.spire.presentation.fileformat;
import com.spire.presentation.presentation;
import com.spire.presentation.slidesizetype;
import com.spire.presentation.charts.chartstyle;
import com.spire.presentation.charts.charttype;
import com.spire.presentation.charts.ichart;
import com.spire.xls.workbook;
import com.spire.xls.worksheet;
import java.awt.geom.rectangle2d;
public class createchartfromexceldata {
public static void main(string[] args) throws exception {
//创建presentation对象
presentation presentation = new presentation();
presentation.getslidesize().settype(slidesizetype.screen_16_x_9);
//添加柱状图
rectangle2d rect = new rectangle2d.float(200, 100, 550, 320);
ichart chart = presentation.getslides().get(0).getshapes().appendchart(charttype.column_clustered,rect);
//清除默认图表数据
chart.getchartdata().clear(0,0,5,5 );
//创建workbook对象并加载excel文档
workbook wb = new workbook();
wb.loadfromfile("c:\\users\\administrator\\desktop\\data.xlsx");
//获取第一个工作表
worksheet sheet = wb.getworksheets().get(0);
//将excel中的数据导入图表数据表
for (int r = 0; r < sheet.getallocatedrange().getrowcount(); r )
{
for (int c = 0; c < sheet.getallocatedrange().getcolumncount(); c )
{
chart.getchartdata().get(r,c).setvalue(sheet.getcellrange(r 1, c 1).getvalue2());
}
}
//添加标题
chart.getcharttitle().gettextproperties().settext("男性女性成员分布");
chart.getcharttitle().gettextproperties().iscentered(true);
chart.getcharttitle().setheight(25f);
chart.hastitle(true);
//设置系列标签
chart.getseries().setserieslabel(chart.getchartdata().get("b1","c1"));
//设置分类标签
chart.getcategories().setcategorylabels(chart.getchartdata().get("a2","a5"));
//设置系列数据
chart.getseries().get(0).setvalues(chart.getchartdata().get("b2","b5"));
chart.getseries().get(1).setvalues(chart.getchartdata().get("c2", "c5"));
//应用内置样式
chart.setchartstyle(chartstyle.style_11);
//设置系列重叠
chart.setoverlap(-50);
//设置分类间距
chart.setgapwidth(200);
//保存文档
presentation.savetofile("output/chart-cn.pptx", fileformat.pptx_2013);
}
}