[英]Apache POI Java - Docx Charts and Graphs
我已經使用XWPF文檔幾周了,我無法添加圖表。 餅圖,條形圖。 我計划手動將帶有XML的圖表注入到文件中,但我認為它過分了。 我只想將圖表添加到Docx模板中。 Aspose和javadocx不是選項。
XWPFDocument document = new XWPFDocument(getClass().getResourceAsStream("/templates/standard.docx"));
//INSERT PIE CHART
FileOutputStream out = new FileOutputStream(new File("output/output.docx");
document.write(out);
[更新 - 輕松路線]
由於成功編寫注入方法需要時間,因此我發現了一種方便(快速,臟)的方法來添加圖表。 這不是正常的單詞圖表,而是從庫中生成的圖表,存儲為圖片並插入。
首先,我從http://knowm.org/open-source/xchart/xchart-example-code下載了該庫。
其次,您已經實現了XWPF文檔,您可以創建一個圖表並將其作為圖像附加。
private XWPFDocument add_chart(XWPFDocument document)
{
// New Chart Element
CategoryChart chart = new CategoryChartBuilder().width(500).height(400).theme(Styler.ChartTheme.GGPlot2).title(getClass().getSimpleName()).build();
chart.setTitle("Issue Count");
// Customize Chart
Color[] sliceColors = new Color[]{new Color(27, 50, 119), new Color(58, 146, 56), new Color(0, 161, 222), new Color(154, 205, 102), new Color(246, 199, 182)};
chart.getStyler().setSeriesColors(sliceColors);
// Series
chart.addSeries("Critical", new ArrayList<>(Arrays.asList(new String[]{"Count"})), new ArrayList<>(Arrays.asList(new Number[]{10})));
chart.addSeries("High", new ArrayList<>(Arrays.asList(new String[]{"High"})), new ArrayList<>(Arrays.asList(new Number[]{5})));
chart.addSeries("Medium", new ArrayList<>(Arrays.asList(new String[]{"Medium"})), new ArrayList<>(Arrays.asList(new Number[]{2})));
chart.addSeries("Low", new ArrayList<>(Arrays.asList(new String[]{"Low"})), new ArrayList<>(Arrays.asList(new Number[]{1})));
// Create and store a jpg image of the chart, then append it to the document
BitmapEncoder.saveBitmapWithDPI(chart, "tmp.jpg", BitmapFormat.JPG, 300);
document.createParagraph().createRun().addPicture(new FileInputStream("tmp.jpg"), XWPFDocument.PICTURE_TYPE_JPEG, "tmp.jpg", Units.toEMU(500), Units.toEMU(400));
return document;
}
您可以使用以下位置的自定義poi jar來讀取和修改文檔文件的圖表,然后寫入您的實際文檔文件。 使用XWPFChart類,您可以使用我們可用於POI EXCEL / PPT的所有方法。
https://github.com/sandeeptiwari32/POI_ENHN/POI3.14.jar
下面是從MS-WORD文件中讀取圖表的簡單示例
public class PoiDocTest {
public static void main(String arg[]) throws FileNotFoundException, IOException
{
@SuppressWarnings("resource")
XWPFDocument document = new XWPFDocument(new FileInputStream("chart.docx"));
@SuppressWarnings("unused")
XWPFChart chart;
for (POIXMLDocumentPart part : document.getRelations()) {
if (part instanceof XWPFChart) {
chart = (XWPFChart) part;
break;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.