/**
* 设置饼图的主方法
* @param slide 图表
* @param index 图标位置
* @param data 需要设置的数据
* @param titles 关联Excel的标题
* @return
*/
public static XSLFSlide setPieChart(XSLFSlide slide, int index, List<String> data, List<String> titles) {
// 获取指定位置的图形
XSLFChart chart = setChartData(slide, index);
List<POIXMLDocumentPart> partList = chart.getRelations();
POIXMLDocumentPart xlsPart = null;
// 获取到内嵌的Excel
for (int i = 0; i < partList.size(); i++) {
xlsPart = partList.get(i);
if (xlsPart.getPackagePart().getPartName().getName().endsWith("xlsx")) {
break;
}
}
CTChart ctChart = chart.getCTChart();
CTPlotArea plotArea = ctChart.getPlotArea();
CTPieChart pieChart = null;
try {
pieChart = plotArea.getPieChartArray(0);
} catch (Exception e) {
log.error("wtx-log:" + e);
}
if (pieChart == null) {
log.info("wtx-log:获取到的扇形图为空。");
return slide;
}
// 获取图表的系列
CTPieSer ser = pieChart.getSerArray(0);
// 把图表绑定到Excel workbook中
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
// 设置列标题,列标题关联
CTSerTx tx = ser.getTx();
sheet.createRow(0).createCell(1).setCellValue(tx.getStrRef().getStrCache().getPtArray(0).getV());
String titleRef = new CellReference(sheet.getSheetName(), 0, 1, true, true).formatAsString();
tx.getStrRef().setF(titleRef);
// 获取行标题
CTAxDataSource cat = ser.getCat();
// 获取原行标题,
CTStrData strData = cat.getStrRef().getStrCache();
strData.setPtArray(null);
for (int i = 0; i < titles.size(); i++) {
CTStrVal sVal = strData.addNewPt();
sVal.setIdx(i);
sVal.setV(titles.get(i));
}
// 获取图表的值
CTNumDataSource val = ser.getVal();
CTNumData numData = val.getNumRef().getNumCache();
// 清除旧的数据值
numData.setPtArray(null);
// 输入新数据
int rownum = 1;
for (int i = 0; i < titles.size(); i++) {
// 设置内存的值
CTNumVal numVal = numData.addNewPt();
numVal.setIdx(i);
numVal.setV(data.get(i));
// 设置workbook的值
XSSFRow row = sheet.createRow(rownum++);
row.createCell(0).setCellValue(titles.get(i));
row.createCell(1).setCellValue(Double.parseDouble(data.get(i)));
}
numData.getPtCount().setVal(titles.size());
strData.getPtCount().setVal(titles.size());
// 设置行标题和数据关联
String numDataRange = new CellRangeAddress(1, titles.size(), 1, 1).formatAsString(sheet.getSheetName(), true);
val.getNumRef().setF(numDataRange);
String axisDataRange = new CellRangeAddress(1, titles.size(), 0, 0).formatAsString(sheet.getSheetName(), true);
cat.getStrRef().setF(axisDataRange);
// 更新嵌入的workbook
updateWorkbook(xlsPart, wb);
return slide;
}
/**
* 更新嵌入的workbook
*
* @param ppt
* @param xlsPart
* @param wb
* @return
*/
private static void updateWorkbook(POIXMLDocumentPart xlsPart, XSSFWorkbook wb) {
// 更新嵌入的workbook
OutputStream xlsOut = xlsPart.getPackagePart().getOutputStream();
try {
wb.write(xlsOut);
} catch (IOException e) {
log.error("PPTUtil.updateWorkbook() :" + e);
} finally {
try {
xlsOut.close();
} catch (IOException e) {
log.error("PPTUtil.updateWorkbook() :" + e);
}
}
}