Java poi导出word文件

这篇博客记录了Java使用POI库导出Word文件时遇到的问题,特别是表格内容垂直居中处理的实现。文章详细介绍了在maven pom.xml中添加POI依赖的步骤,解决ooxml-schemas版本不匹配导致的错误,并提供了controller、service接口和服务业务层的代码结构。同时,展示了WordUtil工具类的使用和最终导出效果。
摘要由CSDN通过智能技术生成

Java在导出word文件时主要对表格中内容垂直居中处理做以记录方便后续碰到类似问题解决。

maven pom.xml中添加poi依赖

<!-- word、excel工具 -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
     <poi.version>4.1.2</poi.version>
</dependency>

下载后查看依赖是否成功

 此时当在wordutil.java类中  CTPageSz 报红是因为ooxml-shemas版本不对需要另外下载1.3版本然后添加到本项目依赖中即可

下载ooxml-shemas1.4版本的依赖pom;注意有些1.3版本太低了,换成1.4版本即可。

<!-- CTPageSz 横向纵向设置 -->
 <dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>ooxml-schemas</artifactId>
     <version>1.4</version>
 </dependency>

poi整个依赖如下:

 

 controller层

package cn.umidata.supervision.dataeye.controller;

import cn.umidata.supervision.biz.service.ReportExWordService;
import cn.umidata.supervision.common.core.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;

/**
 * @BelongsProject: supervision
 * @BelongsPackage: cn.umidata.supervision.dataeye.controller
 * @Author: zhanghui
 * @CreateTime: 2023-04-21  14:29
 * @Description: 报表
 * @Version: 1.0
 */
@Api(tags = "报表导出word")
@RestController
@RequestMapping("/report")
public class ReportController {

    @Autowired
    private ReportExWordService reportExWordService;

//    @ApiOperation(value = "导出监管报告",notes = "导出监管报告")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "dwmc",value = "单位名称",required = true),
//            @ApiImplicitParam(name = "kqmc",value = "库区名称",required = true)
//    })
//    @GetMapping("/exportJG")
//    public AjaxResult exportJG(String dwmc,String kqmc){
//        return reportExWordService.exportJG(dwmc,kqmc);
//    }
    @ApiOperation(value = "导出监管报告",notes = "导出监管报告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dwmc",value = "单位名称",required = true),
            @ApiImplicitParam(name = "kqmc",value = "库区名称",required = true)
    })
    @GetMapping("/exportJG")
    public void exportJG(HttpServletRequest request,
                               HttpServletResponse response, String dwmc, String kqmc) throws IOException {
        XWPFDocument doc = reportExWordService.exportJG(request, response, dwmc,kqmc);
        String fileName = dwmc+kqmc+"监管" + System.currentTimeMillis() + ".docx";
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
        response.setContentType("application/x-msdownload");
        OutputStream out = response.getOutputStream();
        doc.write(out);
    }

    @ApiOperation(value = "导出质量报告",notes = "导出质量报告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dwmc",value = "单位名称",required = true),
            @ApiImplicitParam(name = "kqmc",value = "库区名称",required = true),
            @ApiImplicitParam(name = "datetime",value = "时间",required = true),
    })
    @GetMapping("/exportZL")
    public void exportZL(HttpServletRequest request,
                         HttpServletResponse response, String dwmc, String kqmc, String datetime) throws IOException {
        XWPFDocument doc = reportExWordService.exportZL(request, response, dwmc,kqmc,datetime);
        String fileName = dwmc+kqmc+"质量" + System.currentTimeMillis() + ".docx";
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
        response.setContentType("application/x-msdownload");
        OutputStream out = response.getOutputStream();
        doc.write(out);
    }

    @ApiOperation(value = "导出临时word文件",notes = "导出临时word文件")
    @GetMapping("/exportTmp")
    public void exportTmp(HttpServletRequest request,HttpServletResponse response) throws IOException {
        XWPFDocument doc = reportExWordService.exportTmp(request,response);
        String fileName = "元始天尊" + System.currentTimeMillis() + ".docx";
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
        response.setContentType("application/x-msdownload");
        OutputStream out = response.getOutputStream();
        doc.write(out);
    }
}

Service接口

package cn.umidata.supervision.biz.service;

import cn.umidata.supervision.common.core.domain.AjaxResult;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

public interface ReportExWordService {
    /**
     * @description: 导出监管报告
     * @author: zhanghui
     * @date: 2023/4/27 0027 上午 10:00
     * @param: [request, response, dwmc, kqmc]
     * @return: org.apache.poi.xwpf.usermodel.XWPFDocument
     **/
    XWPFDocument exportJG(HttpServletRequest request, HttpServletResponse response, String dwmc, String kqmc);
    /**
     * @description: 导出质量报告
     * @author: zhanghui
     * @date: 2023/4/27 0027 上午 10:00
     * @param: [request, response, dwmc, kqmc, datetime]
     * @return: org.apache.poi.xwpf.usermodel.XWPFDocument
     **/
    XWPFDocument exportZL(HttpServletRequest request, HttpServletResponse response, String dwmc, String kqmc, String datetime);
    /**
     * @description: 导出临时word文件
     * @author: zhanghui
     * @date: 2023/4/27 0027 上午 10:00
     * @param: [request, response]
     * @return: org.apache.poi.xwpf.usermodel.XWPFDocument
     **/
    XWPFDocument exportTmp(HttpServletRequest request, HttpServletResponse response);


}

service业务层

package cn.umidata.supervision.biz.service.impl;


import cn.umidata.supervision.biz.service.ReportExWordService;
import cn.umidata.supervision.common.utils.poi.WordUtil;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @BelongsProject: supervision
 * @BelongsPackage: cn.umidata.supervision.biz.service.impl
 * @Author: zhanghui
 * @CreateTime: 2023-04-21  14:44
 * @Description: 导出word 报表业务处理
 * @Version: 1.0
 */
@Service
public class ReportExWordServiceImpl implements ReportExWordService {

    /**
     * @description: 导出监管报表word
     * @author: zhanghui
     * @date: 2023/4/21 0021 下午 2:55
     * @param: [dwmc, kqmc]
     * @return: cn.umidata.supervision.common.core.domain.AjaxResult
     **/
    @Override
    public XWPFDocument exportJG(HttpServletRequest request, HttpServletResponse response, String dwmc, String kqmc) {
        Date date = new Date();
        //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //String time = simpleDateFormat.format(date);
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy年MM月dd日");
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy年度M月");
        SimpleDateFormat format3 = new SimpleDateFormat("yyyyMMddHHmmss");
        String ndTime = format2.format(date);
        String tjTime = format1.format(date);
        String bhTime = format3.format(date);

        XWPFDocument doc = new XWPFDocument();
        WordUtil.setH(doc);
        WordUtil.setParagraph(doc,ndTime+"份"+kqmc+"储备粮监管平台储备情况监管报告","宋体",22,100,true,ParagraphAlignment.CENTER);
        WordUtil.setParagraph(doc,"编号:V"+bhTime+"                               "+"统计时间:"+tjTime,"宋体",12,20,true,ParagraphAlignment.CENTER);
        WordUtil.setTitleText(doc,"一、粮食储备整体情况",20,true,false);
        WordUtil.setTable(doc);
        WordUtil.setTitleText(doc,"二、各库区粮食储备详细概况",20,true,false);
        WordUtil.setTableKQ(doc);
        WordUtil.setTitleText(doc,"三、风险预警概况",20,true,false);
        WordUtil.setTableFX(doc);


        return doc;
    }

    /**
     * @description: 质量报告
     * @author: zhanghui
     * @date: 2023/4/24 0024 下午 3:41
     * @param: [request, response, dwmc, kqmc, datetime]
     * @return: org.apache.poi.xwpf.usermodel.XWPFDocument
     **/
    @Override
    public XWPFDocument exportZL(HttpServletRequest request, HttpServletResponse response, String dwmc, String kqmc,String datetime) {
        Date date = new Date();
        SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat format3 = new SimpleDateFormat("yyyyMMddHHmmss");
        String bhTime = format3.format(date);
        String bgTime = format1.format(date);
        XWPFDocument doc = new XWPFDocument();
        WordUtil.setH(doc);
        WordUtil.setParagraph(doc,"陕西省省级储备粮监管信息化平台数据质量报告","宋体",22,100,true,ParagraphAlignment.CENTER);
        WordUtil.setParagraph(doc,"编号:V"+bhTime+"                               "+"统计时间:"+bgTime,"宋体",12,20,true,ParagraphAlignment.CENTER);
        WordUtil.setTableZL(doc,datetime,dwmc);
        XWPFParagraph paragraph = doc.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText("注:1.上传库存指粮食库存接口中粮食性质为省、市、县三级储备的计价数量字段合计(不含孤岛数据);2.实际库存取自各省统计直报系统报送数据;3.实际业务相符率指上传库存/实际库存;4.修正业务相符率指上传库存/实际库存,当业务相符率<=1时,取原值;业务相符率>1时,2-得数;业务相符率>=2时,取0。5.数据上传总量指调用国家平台接口的数据条数合计;6.入库数据总量指上传数据总量通过拦截评测并入库保存的数据;7.问题总数指入库数据中存在的问题数量,一条记录可能有多个问题;8.问题记录数指存在问题的记录条数,问题记录数<=问题总数;9.非空字段总数指所有接口不为空字段的数量合计;10.字段总量指所有接口字段的数量合计;11.接口开通率指已连通的接口个数/所有接口个数;12.通过率指入库数据总量/数据上传总量;13.完整率指上传数据非空字段总数/上传数据的字段总数;14.合格率指∑(各接口合格率*接口系数)。其中,各接口合格率=问题数据条数/入库数据总量;15.评分标准(暂定)。修正业务相符率*(接口开通率*10%+数据通过率*10%+数据完整率*20%+数据合格率*60%),得分精确到小数点后2位。");

        return doc;
    }

/**
     * @description: 导出临时word文件
     * @author: zhanghui
     * @date: 2023/4/26 0026 下午 4:02
     * @param: [request, response]
     * @return: org.apache.poi.xwpf.usermodel.XWPFDocument
     **/
    @Override
    public XWPFDocument exportTmp(HttpServletRequest request, HttpServletResponse response) {
        XWPFDocument doc = new XWPFDocument();
        WordUtil.setParagraph(doc,"十里平湖霜满天","宋体",22,100,true,ParagraphAlignment.CENTER);
        WordUtil.creataTable(doc);
        return doc;
    }

}

WordUtil 工具类

package cn.umidata.supervision.common.utils.poi;

import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.impl.xb.xmlschema.SpaceAttribute;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @BelongsProject: supervision
 * @BelongsPackage: cn.umidata.supervision.common.utils.poi
 * @Author: zhanghui
 * @CreateTime: 2023-04-21  14:57
 * @Description: word相关处理
 * @Version: 1.0
 */
public class WordUtil {


    private static final Logger log = LoggerFactory.getLogger(WordUtil.class);
    //创建默认的页脚(该页脚主要只居中显示页码)
    public static void createDefaultFooter(XWPFDocument docx) {
        CTSectPr sectPr = docx.getDocument().getBody().addNewSectPr();
        XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy(docx, sectPr);
        XWPFFooter footer = headerFooterPolicy.createFooter(STHdrFtr.DEFAULT);
        XWPFParagraph paragraph = footer.getParagraphArray(0);
        paragraph.setAlignment(ParagraphAlignment.CENTER);
        paragraph.setVerticalAlignment(TextAlignment.CENTER);
        CTTabStop tabStop = paragraph.getCTP().getPPr().addNewTabs().addNewTab();
        tabStop.setVal(STTabJc.CENTER);
        XWPFRun run = paragraph.createRun();
        run.addTab();
        run = paragraph.createRun();
        run.setText("第");
        run = paragraph.createRun();
        CTFldChar fldChar = run.getCTR().addNewFldChar();
        fldChar.setFldCharType(STFldCharType.Enum.forString("begin"));
        run = paragraph.createRun();
        CTText ctText = run.getCTR().addNewInstrText();
        ctText.setStringValue("PAGE  \\* MERGEFORMAT");
        ctText.setSpace(SpaceAttribute.Space.Enum.forString("preserve"));
        fldChar = run.getCTR().addNewFldChar();
        fldChar.setFldCharType(STFldCharType.Enum.forString("end"));
        run = paragraph.createRun();
        run.setText("页/共");
        run = paragraph.createRun();
        fldChar = run.getCTR().addNewFldChar();
        fldChar.setFldCharType(STFldCharType.Enum.forString("begin"));
        run = paragraph.createRun();
        ctText = run.getCTR().addNewInstrText();
        ctText.setStringValue("NUMPAGES  \\* MERGEFORMAT ");
        ctText.setSpace(SpaceAttribute.Space.Enum.forString("preserve"));
        fldChar = run.getCTR().addNewFldChar();
        fldChar.setFldCharType(STFldCharType.Enum.forString("end"));
        run = paragraph.createRun();
        run.setText("页");
    }

    /**
     * 设置表头内容
     *
     * @param cell
     * @param text
     * @param width
     * @param fontFamily
     * @param fontSize
     * @param bold
     */
    public static void setCellText(XWPFTableCell cell, String text, int width, String fontFamily, int fontSize, boolean bold) {
        XWPFParagraph paragraph = cell.getParagraphs().get(0);
        XWPFRun run = paragraph.createRun();
        run.setFontFamily(fontFamily);
        run.setFontSize(fontSize);
        run.setBold(bold);
        run.setText(text);
        CTTc cttc = cell.getCTTc();
        CTTcPr cellPr = cttc.addNewTcPr();
        cellPr.addNewTcW().setW(BigInteger.valueOf(width));
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
        CTTcPr ctPr = cttc.addNewTcPr();
        ctPr.addNewVAlign().setVal(STVerticalJc.CENTER);
        cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);
    }
    /**
     * 设置页边距
     *
     * @param doc
     * @param left
     * @param right
     * @param top
     * @param bottom
     */
//    public static void setMargin(XWPFDocument doc, int left, int right, int top, int bottom) {
//        CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
//        CTPageMar pageMar = sectPr.addNewPgMar();
//        pageMar.setLeft(BigInteger.valueOf(left));
//        pageMar.setRight(BigInteger.valueOf(right));
//        pageMar.setTop(BigInteger.valueOf(top));
//        pageMar.setBottom(BigInteger.valueOf(bottom));
//    }

    /**
     * 设置段落文本
     *
     * @param doc
     * @param text
     * @param fontFamily
     * @param fontSize
     * @param textPosition
     * @param bold
     * @param paragraphAlignment
     */
    public static void setParagraph(XWPFDocument doc,
                                    String text,
                                    String fontFamily,
                                    int fontSize,
                                    int textPosition,
                                    boolean bold,
                                    ParagraphAlignment paragraphAlignment) {
        XWPFParagraph xp = doc.createParagraph();
        xp.setSpacingBefore(0);
        XWPFRun r1 = xp.createRun();
        r1.setText(text);
        r1.setFontFamily(fontFamily);
        r1.setFontSize(fontSize);
        r1.setTextPosition(textPosition);
        r1.setBold(bold);
        xp.setAlignment(paragraphAlignment);
    }

    /**
     * @description:  设置为横向
     * @author: zhanghui
     * @date: 2023/4/23 0023 上午 11:34
     * @param: [doc]
     * @return: void
     **/
    public static void setH(XWPFDocument doc){
        CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
        CTPageSz pgsz = sectPr.isSetPgSz() ? sectPr.getPgSz() : sectPr.addNewPgSz();
        //设置横板
        pgsz.setW(BigInteger.valueOf(15840));
        pgsz.setH(BigInteger.valueOf(11907));
        pgsz.setOrient(STPageOrientation.LANDSCAPE);

    }

    /**
     * @description:  设置表格内容
     * @author: zhanghui
     * @date: 2023/4/23 0023 下午 3:16
     * @param: [xdoc, text, fontSize, isBold, isCenter]
     * @return: void
     **/
    public static void setTitleText(XWPFDocument xdoc, String text, Integer fontSize, boolean isBold,boolean isCenter) {
        XWPFParagraph xp = xdoc.createParagraph();
        XWPFRun r1 = xp.createRun();
        r1.setText(text);
        r1.setFontFamily("宋体");
        if(fontSize != null){
            r1.setFontSize(fontSize);
        }
        if(isBold){
            r1.setBold(true);
        }
        if(isCenter){
            xp.setAlignment(ParagraphAlignment.CENTER);
        }
    }

/**
 * @description: 创建表一
 * @author: zhanghui
 * @date: 2023/4/24 0024 上午 11:27
 * @param: [xdoc]
 * @return: void
 **/
  public static void setTable(XWPFDocument xdoc,JgCbzt jgCbzt){
      XWPFTable xTable = xdoc.createTable();//创建表格
      CTTblPr tblPr =xTable.getCTTbl().addNewTblPr(); //内容居中
      tblPr.addNewJc().setVal(STJc.CENTER);
      //兼容wps
      CTTblWidth tblWidth = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr.addNewTblW(); //列宽自动分割
      tblWidth.setW(new BigInteger("1036000"));//总长度
      tblWidth.setType(STTblWidth.AUTO);
      xTable.getRow(0).setHeight(30);//高度
      setBodyTextTmp(xTable.getRow(0).getCell(0), "储备概况", null,true,true,2500);
      setBodyTextTmp(xTable.getRow(0).addNewTableCell(), "监管储备单位(家)", null,true,true,2500);
      setBodyTextTmp(xTable.getRow(0).addNewTableCell(), 3600, null,true,true,2500);
      setBodyTextTmp(xTable.getRow(0).addNewTableCell(), "", null,true,true,2500);
      setBodyTextTmp(xTable.getRow(0).addNewTableCell(), "", null,true,true,2500);
      setBodyTextTmp(xTable.getRow(0).addNewTableCell(), "监管库区(个)", null,true,true,2500);
      setBodyTextTmp(xTable.getRow(0).addNewTableCell(), 3600, null,true,true,2500);
      setBodyTextTmp(xTable.getRow(0).addNewTableCell(), "", null,true,true,2500);
      setBodyTextTmp(xTable.getRow(0).addNewTableCell(), "", null,true,true,2500);
      XWPFTableRow rowTitle2 = xTable.createRow();//第二行表头
      xTable.getRow(0).setHeight(30);
      setBodyTextTmp(rowTitle2.getCell(0), "", null,false,true,2500);
      setBodyTextTmp(rowTitle2.getCell(1), "仓房(个)", null,false,true,2500);
      setBodyTextTmp(rowTitle2.getCell(2), 3600, null,false,true,2500);
      setBodyTextTmp(rowTitle2.getCell(3), "廒间(个)", null,false,true,2500);
      setBodyTextTmp(rowTitle2.getCell(4), 3600, null,false,true,2500);
      setBodyTextTmp(rowTitle2.getCell(5), "货位(个)", null,false,true,2500);
      setBodyTextTmp(rowTitle2.getCell(6), 3600, null,false,true,2500);
      setBodyTextTmp(rowTitle2.getCell(7), "油罐(个)", null,false,true,2500);
      setBodyTextTmp(rowTitle2.getCell(8), 3600, null,false,true,2500);
      XWPFTableRow rowTitle3 = xTable.createRow();//第三行表头
      xTable.getRow(0).setHeight(30);
      setBodyTextTmp(rowTitle3.getCell(0), "", null,false,true,2500);
      setBodyTextTmp(rowTitle3.getCell(1), "总仓容(万吨)", null,false,true,2500);
      setBodyTextTmp(rowTitle3.getCell(2), 3600, null,false,true,2500);
      setBodyTextTmp(rowTitle3.getCell(3), "", null,false,true,2500);
      setBodyTextTmp(rowTitle3.getCell(4), "", null,false,true,2500);
      setBodyTextTmp(rowTitle3.getCell(5), "已用仓容(万吨)", null,false,true,2500);
      setBodyTextTmp(rowTitle3.getCell(6), 3600, null,false,true,2500);
      setBodyTextTmp(rowTitle3.getCell(7), "未用仓容(万吨)", null,false,true,2500);
      setBodyTextTmp(rowTitle3.getCell(8), 3600, null,false,true,2500);
      XWPFTableRow rowTitle4 = xTable.createRow();
      xTable.getRow(0).setHeight(30);
      setBodyTextTmp(rowTitle4.getCell(0), "粮食数量", null,true,true,2500);
      setBodyTextTmp(rowTitle4.getCell(1), "监管粮食储备总量(万吨)", null,false,true,2500);
      setBodyTextTmp(rowTitle4.getCell(2), 3600, null,false,true,2500);
      setBodyTextTmp(rowTitle4.getCell(3), "", null,false,true,2500);
      setBodyTextTmp(rowTitle4.getCell(4), "", null,false,true,2500);
      setBodyTextTmp(rowTitle4.getCell(5), "", null,false,true,2500);
      setBodyTextTmp(rowTitle4.getCell(6), "", null,false,true,2500);
      setBodyTextTmp(rowTitle4.getCell(7), "", null,false,true,2500);
      setBodyTextTmp(rowTitle4.getCell(8), "", null,false,true,2500);
      XWPFTableRow rowTitle5 = xTable.createRow();
      xTable.getRow(0).setHeight(30);
      setBodyTextTmp(rowTitle5.getCell(0), "", null,false,true,2500);
      setBodyTextTmp(rowTitle5.getCell(1), "一小麦(万吨)", null,false,true,2500);
      setBodyTextTmp(rowTitle5.getCell(2), 3600, null,false,true,2500);
      setBodyTextTmp(rowTitle5.getCell(3), "二小麦(万吨)", null,false,true,2500);
      setBodyTextTmp(rowTitle5.getCell(4), 3600, null,false,true,2500);
      setBodyTextTmp(rowTitle5.getCell(5), "玉米(万吨)", null,false,true,2500);
      setBodyTextTmp(rowTitle5.getCell(6), 3600, null,false,true,2500);
      setBodyTextTmp(rowTitle5.getCell(7), "稻谷(万吨)", null,false,true,2500);
      setBodyTextTmp(rowTitle5.getCell(8), 3600, null,false,true,2500);
      XWPFTableRow rowTitle6 = xTable.createRow();
      xTable.getRow(0).setHeight(30);
      setBodyTextTmp(rowTitle6.getCell(0), "", null,false,true,2500);
      setBodyTextTmp(rowTitle6.getCell(1), "省级储备粮(万吨)", null,false,true,2500);
      setBodyTextTmp(rowTitle6.getCell(2), 3600, null,false,true,2500);
      setBodyTextTmp(rowTitle6.getCell(3), "市级储备粮(万吨)", null,false,true,2500);
      setBodyTextTmp(rowTitle6.getCell(4), 3600, null,false,true,2500);
      setBodyTextTmp(rowTitle6.getCell(5), "商品粮(万吨)", null,false,true,2500);
      setBodyTextTmp(rowTitle6.getCell(6), 3600, null,false,true,2500);
      setBodyTextTmp(rowTitle6.getCell(7), "", null,false,true,2500);
      setBodyTextTmp(rowTitle6.getCell(8), "", null,false,true,2500);
      XWPFTableRow rowTitle7 = xTable.createRow();
      xTable.getRow(0).setHeight(30);
      setBodyTextTmp(rowTitle7.getCell(0), "", null,false,true,2500);
      setBodyTextTmp(rowTitle7.getCell(1), "2023年(万吨)", null,false,true,2500);
      setBodyTextTmp(rowTitle7.getCell(2), 3600, null,false,true,2500);
      setBodyTextTmp(rowTitle7.getCell(3), &#
### 回答1: Java POI 是一个用于操作 Microsoft Office 格式文件Java 库,包括 Word、Excel 和 PowerPoint 等文件。在 Java 中使用 POI 库可以方便地读取、修改和创建 Office 文件。 在使用 POI 导出 Word 文档时,需要先创建一个空的 Word 文档,然后向其中添加内容。可以使用 POI 提供的 XWPFDocument 类来创建 Word 文档对象,使用 XWPFParagraph 类来创建段落对象,使用 XWPFRun 类来创建文本对象。 在创建段落对象时,可以设置段落的样式,如字体、字号、颜色、对齐方式等。在创建文本对象时,可以设置文本的样式,如加粗、斜体、下划线等。 除了文本内容,还可以向 Word 文档中添加表格、图片、超链接等元素。可以使用 POI 提供的 XWPFTable 类来创建表格对象,使用 XWPFTableRow 和 XWPFTableCell 类来创建表格行和单元格对象。可以使用 XWPFParagraph 类的 addPicture 方法来添加图片,使用 XWPFHyperlink 类来添加超链接。 最后,将创建好的 Word 文档保存到本地文件系统或输出流中即可。可以使用 XWPFDocument 类的 write 方法将文档保存到文件中,使用 XWPFDocument 类的 write 方法将文档输出到输出流中。 总之,使用 Java POI 导出 Word 文档需要掌握 XWPFDocument、XWPFParagraph、XWPFRun、XWPFTable、XWPFTableRow、XWPFTableCell、XWPFHyperlink 等类的使用方法,以及如何设置样式、添加元素和保存文档。 ### 回答2: Java POI是一个流行的Java库,它提供了对微软Office格式的读取和写入支持,其中包括Word文档的导出。在使用此库导出Word文档时,可以按照以下步骤进行操作: 第一步:导入所需的库文件和工具 我们需要导入Apache POI库以及相关的库文件来使用Java POI。可以从maven中央仓库中下载这些库文件,也可以通过其他方式来获取这些文件。在项目中添加所需的库文件,并在相关的类中导入这些库文件。 第二步:创建Word文档 在Java中,可以使用XWPFDocument类来创建一个空白的Word文档。在此类中,可以添加标题,正文文本,表格等内容,以构建新的Word文档。可以使用以下代码来创建一个新的Word文档。 XWPFDocument doc = new XWPFDocument(); 第三步:添加内容 在Java POI中,可以使用XWPFParagraph类来添加Word文档中的段落。可以使用此类来添加文字,图片等。以下是如何使用XWPFParagraph类来添加段落的示例代码: XWPFParagraph para = doc.createParagraph(); XWPFRun run = para.createRun(); run.setText("这是一个段落"); 可以使用XWPFTable类来添加Word文档中的表格。以下是如何使用XWPFTable类来添加表格的示例代码: XWPFTable table = doc.createTable(); XWPFTableRow row = table.getRow(0); row.getCell(0).setText("第一行第一列"); row.addNewTableCell().setText("第一行第二列"); 第四步:保存文档 完成了Word文档的创建和内容添加之后,需要将其保存到磁盘上。可以使用FileOutputStream类和XWPFDocument类的write() 方法来完成保存。以下代码片段演示了如何将文档保存到磁盘上: FileOutputStream outputStream = new FileOutputStream(new File("output.docx")); doc.write(outputStream); outputStream.close(); 总结 Java POI提供了一种通过代码来创建和编辑Word文档的方式。使用Java POI,我们可以创建空白的Word文档,向文档中添加内容,例如文字,图片和表格。最后,我们可以将文档保存到磁盘上。通过这些步骤,我们可以轻松地使用Java POI导出Word文档。 ### 回答3: Java POI是一个开源的Java库,用于处理各种Microsoft Office格式文件,包括Word文档(.docx)、Excel表格(.xlsx)和PowerPoint演示文稿(.pptx)。在Java POI中,我们可以使用XWPFDocument对象导出Word文档。 1. 导入依赖 在使用Java POI库之前,首先必须要引入相应的依赖包。我们需要使用以下依赖: ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 2. 创建一个Word文档 我们可以使用XWPFDocument类创建一个新的Word文档。默认情况下,文档中没有任何内容: ``` XWPFDocument document = new XWPFDocument(); ``` 3. 添加标题 添加标题可以使用XWPFParagraph和XWPFRun类。XWPFParagraph用于存储段落内容,而XWPFRun用于添加样式。以下是一个添加标题的示例代码: ``` XWPFParagraph titlePara = document.createParagraph(); XWPFRun titleRun = titlePara.createRun(); titleRun.setBold(true); titleRun.setFontSize(16); titleRun.setText("这是一个标题"); ``` 4. 添加正文 添加正文和添加标题类似,只不过我们可以在添加文本之前使用setBold、setItalic、setUnderline等方法设置样式。以下是添加正文的示例代码: ``` XWPFParagraph contentPara = document.createParagraph(); XWPFRun contentRun = contentPara.createRun(); contentRun.setFontSize(12); contentRun.setText("这是一个正文"); ``` 5. 添加图片 在Word文档中添加图片可以使用XWPFRun类的addPicture方法。需要注意的是,图片必须先被转换为byte数组。以下是添加图片的示例代码: ``` // 读取图片文件 FileInputStream fis = new FileInputStream("path/to/image.png"); byte[] imageData = IOUtils.toByteArray(fis); fis.close(); // 添加图片 XWPFParagraph imagePara = document.createParagraph(); XWPFRun imageRun = imagePara.createRun(); imageRun.addPicture(new ByteArrayInputStream(imageData), XWPFDocument.PICTURE_TYPE_PNG, "image.png", Units.toEMU(300), Units.toEMU(200)); ``` 6. 保存文档 在完成文档的内容添加后,我们可以将文档保存到指定的文件中。以下是保存文档的示例代码: ``` OutputStream os = new FileOutputStream("path/to/output.docx"); document.write(os); os.close(); document.close(); ``` 以上就是使用Java POI导出Word文档的详细步骤。通过使用Java POI,我们可以方便地创建和编辑Word文档,并将其保存为docx格式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值