想实现代码改变数据,然后刷新透视图,然后同时刷新根据透视图生成的图表,保存为图片。使用pt.calculateData()刷新,有问题,个别文档生效,个别文档无效,不知道为什么,还是老的数据。反馈给厂商,客服说是BUG,已经提交,现在使用aspose代替https://blog.csdn.net/a3562323/article/details/123273445
设置文档打开时刷新透视表数据
//获取透视表,刷新数据
PivotTable pivotTable = (PivotTable) sheet.getPivotTables().get(0);
pivotTable.getCache().isRefreshOnLoad(true);
代码刷新透视表数据
XlsPivotTable pt= (XlsPivotTable) wb.getWorksheets().get(0).getPivotTables().get(0);
pt.calculateData();
图表
获取图表类型
Workbook workbook = new Workbook();
workbook.loadFromFile("C:\\Users\\w4523\\Desktop\\新建文件夹 (3)\\chart2_66.xlsm");
ExcelChartType chartType = workbook.getWorksheets().get(0).getCharts().get(0).getChartType();
System.out.println(chartType.toString());
创建图表
//创建一个新的chart
Chart chart = sheet.getCharts().add();
//设置图表的类型
chart.setChartType( ExcelChartType.ColumnClustered);
//chart数据源的范围
chart.setDataRange(sheet.getCellRange("E10:F17"));
chart.setSeriesDataFromRange(false);
//set 生成图表的位置
chart.setLeftColumn(4);
chart.setTopRow(2);
chart.setRightColumn(12);
chart.setBottomRow(22);
//chart 标题
chart.setChartTitle("Market share by country");
chart.getChartTitleArea().isBold(true );
chart.getChartTitleArea().setSize(12);
for( int i =0; i<chart.getSeries().getCount();i++)
{
ChartSerie cs = chart.getSeries().get(i);
cs.getDataPoints().getDefaultDataPoint().getDataLabels().hasPercentage(true);
}
//设置图例不显示
chart.getLegend().setPosition( LegendPositionType.NotDocked);
chart.hasChartTitle(false);
//save the document
workbook.saveToFile("d:\\保存的位置", ExcelVersion.Version2013);
保存chart为图片
//创建实例
Workbook wb = new Workbook();
//加载Excel
wb.loadFromFile("C:\\Users\\w4523\\Desktop\\新建文件夹 (3)\\spireSample\\createPviotTable.xlsx");
//将Excel文档第一个工作表中的第一个图表保存为图片
BufferedImage image = wb.saveChartAsImage(wb.getWorksheets().get(0), 0);
//new File()输出位置
ImageIO.write(image, "png", new File("C:\\Users\\w4523\\Desktop\\新建文件夹 (3)\\123.png"));
spire官网API:https://www.evget.com/article/2019/1/11/29299.html
博客内容讲述了在处理Excel文件时遇到的一个问题,即使用pt.calculateData()方法刷新透视表数据,结果出现部分文档生效,部分文档无效的情况。厂商确认为BUG并推荐使用Aspose替代。代码示例展示了如何设置透视表在打开时自动刷新,以及如何创建和修改图表,最后保存图表为图片。解决方案是通过Spire.XLS库来实现这些功能。

2万+

被折叠的 条评论
为什么被折叠?



