XWPFDocument生成word保存到本地

package com.test.controller;

import com.test.util.WordUtils;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class WordTestController {
    public static void main(String[] args) throws IOException {
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        List<String>  stringList=new ArrayList<>();
        String str="Pig中Url的访问大致分为两种,一种是由Gateway网关从外网路由进来,一种是内网通过Feign进行内部服务调用。那我们结合Security就存在以下几种应用场景:\r\n" +
                "1.外部从Gateway访问,需要鉴权(eg.CURD操作)。这种是最常使用的,用户登录后正常访问接口,不需要我们做什么处理(可能有的接口需要加权限字段)。\r\n" +
                "2.外部从Gateway访问,不需要鉴权(eg.短信验证码)。需要我们将uri加入到security.oauth2.client.ignore-urls配置中,可以不需要鉴权访问";
        for(int i=0;i<2;i++){
            stringList.add(str.trim());
            stringList.add(" ");
        }
        WordUtils.getWord(stringList).write(bao);

        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream("D:\\aaa.docx");
            fileOutputStream.write(bao.toByteArray());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
package com.test.util;

import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.util.List;

public class WordUtils {
    public static XWPFDocument getWord(List<String> list) {
        XWPFDocument doc = new XWPFDocument();
        for (String s : list) {
            XWPFParagraph para = doc.createParagraph();
            XWPFRun run = para.createRun();
            para.setAlignment(ParagraphAlignment.LEFT);
            run.setBold(true);
            run.setFontFamily("宋体");
            run.setFontSize(12);
            run.setText(s);
        }
        return doc;
    }
}

你可能感兴趣的:(XWPFDocument生成word保存到本地)