Microsoft® Excel 文件图表转换与创建 via Java
将 Excel 文档图表转换为图像,并在基于 Java 的应用程序中使用服务器端 API 创建各种图表。
通过图表分析数据可以显示更大的图景,并且可以通过更清晰的见解轻松做出更明智的决策。 Java Excel 库 支持绘制列出的不同图表创建 图表类型 包括饼图、金字塔图、折线图和气泡图。此外,它还将图表转换为图像。 API 提供 图表类 用于表示单个 Excel 图表。
将 Excel 图表转换为图像
将图表转换为图像(包括 JPG、PNG、TIFF、BMP 等)的过程是,使用 练习册 加载Excel文件的类,选择相关 工作区 包含图表或迭代每个工作表中的每个图表。定义 图像或打印选项 并使用渲染图表的输出图像 图表转图像 .
Java 将Excel图表转换为图像的代码
// Load input XLSX file | |
Workbook wkb = new Workbook(dataDir + "SampleExcel.xlsx"); | |
for (int sht = 0 ; sht < wkb.getWorksheets().getCount() ; sht++) | |
{ | |
// Access required worksheet | |
Worksheet wks = wkb.getWorksheets().get(sht); | |
for (int i =0 ; i< wks.getCharts().getCount() ; i++) | |
{ | |
// Access specific chart | |
com.aspose.cells.Chart chart = wks.getCharts().get(i); | |
// Create an instance of ImageOrPrintOptions and set a few properties | |
ImageOrPrintOptions options = new ImageOrPrintOptions(); | |
options.setVerticalResolution(300); | |
options.setHorizontalResolution(300); | |
options.setQuality(100); | |
// Set image type for output format | |
options.setImageType(com.aspose.cells.ImageType.PNG); | |
// Render the chart to image | |
chart.toImage(dataDir + "chart_" + (i+1) + "_" + wks.getName() + ".png", options); | |
} | |
} |
在 Excel 文件中创建图表
使用 Excel API 创建图表很简单,因为 API 为不同类型的图表提供了一组不同的类,例如 Axis、Chart、ChartArea、ChartDataTable、ChartFrame、ChartPoint、ChartPointCollection、ChartCollection 等。过程是,创建 Workbook 类对象并通过提供其索引来选择第一个工作表或相关工作表。对于图表的数据源,使用以下命令将值插入工作表单元格 设定值 方法。使用 ChartCollection 集合[添加方法]( https://reference.aspose.com/cells/java/com.aspose.cells/chartcollection#add(int,%20int,%20int,%20int,%20int) 要添加图表,请使用 ChartType 枚举定义图表类型。通过传递索引从 ChartCollection 集合中访问新的 Chart 对象。使用 系列合集 图表对象来指定图表的数据源。
Java 创建 Excel 图表的代码
// Instantiating a Workbook object | |
Workbook wkb = new Workbook(); | |
// Obtaining the reference of the first worksheet | |
WorksheetCollection wks = wkb.getWorksheets(); | |
Worksheet sheet = wks.get(0); | |
// Adding some sample value to cells | |
Cells cells = sheet.getCells(); | |
Cell cell = cells.get("A1"); | |
cell.setValue(50); | |
cell = cells.get("A2"); | |
cell.setValue(100); | |
cell = cells.get("A3"); | |
cell.setValue(150); | |
cell = cells.get("B1"); | |
cell.setValue(4); | |
cell = cells.get("B2"); | |
cell.setValue(20); | |
cell = cells.get("B3"); | |
cell.setValue(50); | |
ChartCollection charts = sheet.getCharts(); | |
// Adding a chart to the worksheet | |
int chartIndex = charts.add(ChartType.PYRAMID, 5, 0, 15, 5); | |
Chart chart = charts.get(chartIndex); | |
// Adding NSeries (chart data source) to the chart ranging from "A1" | |
// cell to "B3" | |
SeriesCollection serieses = chart.getNSeries(); | |
serieses.add("A1:B3", true); | |
// Saving the Excel file | |
wkb.save(dataDir + "Created-pyramid-chart_out.xls"); |