aspose-words简单使用

本文介绍了如何使用Aspose.Words21.1forJava在Word文档中追加内容,包括文本插入和居中,以及如何插入折线图并自定义其样式。实例展示了如何创建新的段落、设置格式和保存为新文档。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值