SpringBoot导出word(兼容office和wps)输入输出流,1分钟学会

来讲一下java中的word,在这之前也查过不少资料,问过不少人,但是在网上找到的资源都是导出到本地,而且要定义一个本地模板,这种方法实在过于局限,不太建议使用,因为以前导出过excel,所以就按照以前导出excel的方式来思考怎么导出word,最后终于实现,请看代码:


import org.apache.poi.xwpf.usermodel.XWPFDocument;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

/**
 *@Author jcc
 *@Description word导出
 *@Date 2019/4/29 14:59
 **/
public class WordUtil {
    public void exportWord(XWPFDocument document, HttpServletResponse response,String fileName) throws Exception{
        response.setHeader("Content-Disposition","attachment;fileName="+ fileName+".docx");
        response.setContentType("application/msword");
        OutputStream os = response.getOutputStream();
        document.write(os);
        os.flush();
        os.close();
    }

}

这是一个导出的工具类,也是自己仿照导出excel写的,可以直接用,但是前提是要导入poi依赖

     
        
            com.deepoove
            poi-tl
            0.0.3
        

然后就可以传入自己的数据了

 @GetMapping("PoiWord")
    @ApiOperation(value = "导出word",notes = "导出word")
    public void PoiWord(String entityId, String structId, String pStructureId, HttpServletResponse response){
        XWPFDocument document= new XWPFDocument();
        try {
        // 这里写你在数据库中查出的数据
            List oralHisStructureTexts=iOralHisStructureTextService.getOralHisStructureText(structId,pStructureId,entityId);
            //然后循环你的数据,因为有多条,不想循环就直接set
            for (OralHisStructureText oralHisStructureText:oralHisStructureTexts){
                //添加标题
                XWPFParagraph titleParagraph = document.createParagraph();
                //设置段落居中
                titleParagraph.setAlignment(ParagraphAlignment.CENTER);

                // 标题
                XWPFRun titleParagraphRun = titleParagraph.createRun();
                // 然后把你查出的数据插入到document中去就可以了
                titleParagraphRun.setText(oralHisStructureText.getStructureName());
                // 设置字体颜色
                titleParagraphRun.setColor("000000");
                // 设置字体大小
                titleParagraphRun.setFontSize(15);

                //段落
                XWPFParagraph firstParagraph = document.createParagraph();
                XWPFRun run = firstParagraph.createRun();
                run.setText(oralHisStructureText.getContent());
                run.setColor("000000");
                run.setFontSize(10);
                //换行
                XWPFParagraph paragraph1 = document.createParagraph();
                XWPFRun paragraphRun1 = paragraph1.createRun();
                paragraphRun1.setText("\r");
            }
            SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmmss");
            String fileName = new String("word导出".getBytes("UTF-8"), "iso-8859-1");
            new WordUtil().exportWord(document,response,fileName+sdf.format(new Date()));
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        System.out.println("导出成功!!!!");
        }

你可能感兴趣的:(java)