简体   繁体   中英

Using SingleSeriesCharts in Apache POI-TL

I am trying to include a Pie/Bar Chart in an MSWord docx template. I have written the code as described in the documentation. However, I do not know how to tag or name the chart on the template to ensure it is read from the code. Here is my code:

Map<String, Object> map = new HashMap<>();
String c[] = {"Male", "Female", "Others"};
Number x[] = {23,13.4,11};
File t = new File(System.getProperty("user.dir")+"/chart.docx");
ChartSingleSeriesRenderData pie = Charts.ofSingleSeries("Test", c).series("data", x).create();
map.put("chart", pie);


XWPFTemplate.compile(t).render(map).writeToFile("out.docx");

We are talking about that POI-TL : http://deepoove.com/poi-tl/ and https://github.com/Sayi/poi-tl .

How to use a label for single series charts in the template is documented here 7.3. Single Series Charts :

The label for a single series chart is one text: {{var}}, the label position is: chart area format - alternative text - title (the new version of Microsoft Office label location is: Edit alt text - alt text).

Note: Documentarion is all in Chinese. But modern browsers should be able to translate into English.

So insert a pie chart into the template. Then add alt text . For the chart, right-click the chart object and select Edit Alt Text . In the alt-text-field you can write the label {{chart}}.

My template.docx looks like so:

在此处输入图像描述

Now following code should replace the chart data with the given data in data model.

import java.util.*;

import com.deepoove.poi.*;
import com.deepoove.poi.data.*;
import com.deepoove.poi.data.style.*;

public class TestPOITL {

 public static void main(String[] args) throws Exception {
  Map<String, Object> dataMap = new HashMap<>();
  dataMap.put("title", "Title inserted by POI-TL");
  String[] c = {"Male", "Female", "Others"};
  Number[] x = {23,13.4,11};
  String[] xS = Arrays.stream(x).mapToDouble(v -> v.doubleValue()).mapToObj(String::valueOf).toArray(String[]::new);
  dataMap.put("table", Tables.of(new String[][] {c, xS}).border(BorderStyle.DEFAULT).create());
  ChartSingleSeriesRenderData pie = Charts.ofSingleSeries("Test", c).series("data", x).create();
  dataMap.put("chart", pie);
  XWPFTemplate.compile("./template.docx").render(dataMap).writeToFile("./out.docx");
 }
}

Resulting out.docx looks like so:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM