aspose-words简单使用
版本aspose-words-21.1-jdk17.jar
1、在word文档后面追加内容
try {
// 加载文档
Document doc = new Document("old.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
// 插入段落,添加内容
Paragraph para1 = new Paragraph(doc);
// 创建一个段落格式对象并设置对齐方式为居中
ParagraphFormat paragraphFormat = para1.getParagraphFormat();
paragraphFormat.setAlignment(ParagraphAlignment.CENTER); // 设置居中
Run run = new Run(doc, "要插入的文字内容");
run.getFont().setName("宋体");
run.getFont().setSize(18);
// 将Run对象添加到段落中(没有下面两行代码会添加到文档最前面)
para1.appendChild(run);
doc.getLastSection().getBody().appendChild(para1);
// 把流返回给前端
String fileName = "new.docx";
HttpServletResponse response = HttpServletUtil.getResponse();
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, CharsetUtil.UTF_8));
OutputStream outputStream = response.getOutputStream();
SaveOutputParameters save = doc.save(outputStream, SaveFormat.DOCX);
response.setContentType(save.getContentType());
outputStream.close();
} catch (Exception e) {
}
2、在word文档生成折线图
@Test
public void test1() throws Exception {
Document doc = new Document("old.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
// 1、插入段落
Paragraph para1 = new Paragraph(doc);
// 创建一个段落格式对象并设置对齐方式为居中
ParagraphFormat paragraphFormat = para1.getParagraphFormat();
paragraphFormat.setAlignment(ParagraphAlignment.CENTER); // 设置居中
Run run = new Run(doc, "标题内容");
run.getFont().setName("宋体");
run.getFont().setSize(18);
// 将Run对象添加到段落中
para1.appendChild(run);
doc.getLastSection().getBody().appendChild(para1);
// 2、插入折线图
Shape shape = builder.insertChart(ChartType.LINE, 432, 252);
Chart chart = shape.getChart();
chart.getLegend().setPosition(LegendPosition.NONE);
// 获取X轴对象
ChartAxis xAxis = chart.getAxisX();
// 设置刻度标签位置为底部(数据有负数,x轴也在最下方)
xAxis.setTickLabelPosition(AxisTickLabelPosition.LOW);
ChartSeriesCollection series = chart.getSeries();
// 清空折线图原数据(必须清空,不然会有折线图的原数据存在)
series.clear();
String title = "Line Chart Title";
String[] yData = new String[]{"一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"};
double[] xData = new double[]{2d,4d,1d,-6d,8d,2d,1d,2d,4d,1d,5d,0d};
series.add(title, yData, xData);
series.get(0).setSmooth(true); // 将折线图转换为弧线图
// 3、插入段落,把折线图添加到段落
Paragraph para2 = new Paragraph(doc);
// 把折线图添加到段落
para2.appendChild(shape);
doc.getLastSection().getBody().appendChild(para2);
doc.save("new.docx");
}