poi导出word表格

475 阅读4分钟

由于从maven仓库引的poi跟官网的poi缩减了,有些方法找不到 得另外引一个包

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>ooxml-schemas</artifactId>
    <version>1.4</version>
</dependency>

导出的具体方法

public ModelAndView exportWork(HttpServletRequest request, HttpServletResponse response) {
    Map<String, Object> param = new HashMap<String, Object>();
    String id = request.getParameter("id");
    param.put("holidaydutyid", id);
    Holidayduty holidayduty = holidaydutyService.findHolidaydutyById(id);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
    String holidayname = holidayduty.getHolidayname();
    Long starttime = holidayduty.getStarttime();

    String type = request.getParameter("type");

    String title = type + sdf.format(new Date(starttime)) + "年“" + holidayname + "”值班表";

    //创建一个word对象
    XWPFDocument xwpfDocument = new XWPFDocument();

    CTDocument1 ctDoc = xwpfDocument.getDocument();
    CTBody ctBody = ctDoc.getBody();
    if (!ctBody.isSetSectPr()) {
        ctBody.addNewSectPr();
    }
    CTSectPr ctSectPr = ctBody.getSectPr();
    if (!ctSectPr.isSetPgSz()) {
        ctSectPr.addNewPgSz();
    }

    //创建一个段落(标题)
    XWPFParagraph titleParagraph = xwpfDocument.createParagraph();
    //设置行间距
    setLineSpacing(titleParagraph, 1100);
    //将该段落居中显示
    titleParagraph.setAlignment(ParagraphAlignment.CENTER);
    titleParagraph.setVerticalAlignment(TextAlignment.CENTER);
    //XWPFRun是文本对象!
    XWPFRun xwpfRun = titleParagraph.createRun();
    //设置标题
    xwpfRun.setText(title);
    //设置标题加粗
    //xwpfRun.setBold(true);
    //标题字体大小
    xwpfRun.setFontSize(22);
    xwpfRun.setFontFamily("方正小标宋_GBK");

    XWPFTableCell xtCell;
    XWPFParagraph xtp = null;
    XWPFRun xr = null;
    List<XWPFParagraph> xpList;
    CTTcPr cttcPr = null;
    CTTblWidth ctTblWidth = null;

    Map odMap = new HashMap();
    odMap.put("type", type);
    List<OrganiseDefine> odList = organiseDefineService.findByMulitConditionList(odMap);
    List bmlist = new ArrayList();
    for (OrganiseDefine o : odList) {
        bmlist.add(o.getOrgid());
    }
    param.put("bmlist", bmlist);

    List<List<Map<String, Object>>> result = dutypersonService.daochu(param);

    if (result.size() > 0) {

        //基本信息表格
        XWPFTable infoTable = xwpfDocument.createTable();
        //去表格边框
        //infoTable.getCTTbl().getTblPr().unsetTblBorders();

        if ("各部门".equals(type)) {

            //设置页面为布局
            setParperLayout(ctSectPr, infoTable, 11907, 16840, STPageOrientation.PORTRAIT, 1620, 1520, 1620, 1520, 8667);

            //表格第一行
            XWPFTableRow infoTableRowOne = infoTable.getRow(0);
            //第一行第一列
            xtCell = infoTableRowOne.getCell(0);
            xpList = xtCell.getParagraphs();//因为有一个空白行,这两句话是删除空白行
            xtCell.removeParagraph(xpList.size() - 1);
            //设置段落
            xtp = xtCell.addParagraph();
            xr = xtp.createRun();
            setCellParagraph(xtp, xr, 14, "仿宋_GB2312", "日期");
            //        xr.setBold(true);
            //设置表格列宽度
            cttcPr = xtCell.getCTTc().addNewTcPr();
            ctTblWidth = cttcPr.addNewTcW();
            setCellWidth(ctTblWidth, 2000);

            xtCell = infoTableRowOne.addNewTableCell();
            xpList = xtCell.getParagraphs();//因为有一个空白行,这两句话是删除空白行
            xtCell.removeParagraph(xpList.size() - 1);
            //设置段落
            xtp = xtCell.addParagraph();
            xr = xtp.createRun();
            setCellParagraph(xtp, xr, 14, "仿宋_GB2312", "值班人员");
            //设置行间距
            setLineSpacing(xtp, 600);

            for (int i = 0; i < result.size(); i++) {
                List<Map<String, Object>> list = result.get(i);
                Map map = list.get(0);

                XWPFTableRow xwpfTableRow = infoTable.createRow();
                xtCell = xwpfTableRow.getCell(0);
                xpList = xtCell.getParagraphs();//因为有一个空白行,这两句话是删除空白行
                xtCell.removeParagraph(xpList.size() - 1);

                //设置段落
                xtp = xtCell.addParagraph();
                xr = xtp.createRun();
                setCellParagraph(xtp, xr, 14, "仿宋_GB2312", map.get("zbsj").toString());
                //设置行间距
                setLineSpacing(xtp, 600);

                //设置段落
                xtp = xtCell.addParagraph();
                xr = xtp.createRun();
                setCellParagraph(xtp, xr, 14, "仿宋_GB2312", getWeek(Long.parseLong(map.get("DUTYTIME").toString())));
                //设置行间距
                setLineSpacing(xtp, 600);
                //设置表格列宽度
                cttcPr = xtCell.getCTTc().addNewTcPr();
                ctTblWidth = cttcPr.addNewTcW();
                setCellWidth(ctTblWidth, 2000);

                StringBuffer buffer = new StringBuffer();

                for (Map<String, Object> person : list) {
                    buffer.append(person.get("BMMC")).append(":(").append(map.get("PERSONS") == null ? "" : map.get("PERSONS") + "").append(");");
                }

                xtCell = xwpfTableRow.getCell(1);
                xtCell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                xpList = xtCell.getParagraphs();//因为有一个空白行,这两句话是删除空白行
                xtCell.removeParagraph(xpList.size() - 1);

                //设置段落
                xtp = xtCell.addParagraph();
                xr = xtp.createRun();
                setCellParagraph(xtp, xr, 14, "仿宋_GB2312", buffer.toString());
            }


        } else {

            //设置页面布局
            setParperLayout(ctSectPr, infoTable, 16840, 11907, STPageOrientation.LANDSCAPE, 1620, 1520, 1620, 1520, 13600);

            //表格第一行
            XWPFTableRow infoTableRowOne = infoTable.getRow(0);
            //第一行第一列
            xtCell = infoTableRowOne.getCell(0);
            xpList = xtCell.getParagraphs();//因为有一个空白行,这两句话是删除空白行
            xtCell.removeParagraph(xpList.size() - 1);

            //设置段落
            xtp = xtCell.addParagraph();
            xr = xtp.createRun();
            setCellParagraph(xtp, xr, 14, "仿宋_GB2312", "部门");
            //xr.setBold(true);
            //设置表格列宽度
            cttcPr = xtCell.getCTTc().addNewTcPr();
            ctTblWidth = cttcPr.addNewTcW();
            setCellWidth(ctTblWidth, 2500);

            for (int i = 0; i < result.size(); i++) {

                Map<String, Object> dutytime = result.get(i).get(0);

                xtCell = infoTableRowOne.addNewTableCell();
                xpList = xtCell.getParagraphs();//因为有一个空白行,这两句话是删除空白行
                xtCell.removeParagraph(xpList.size() - 1);

                //设置段落
                xtp = xtCell.addParagraph();
                xr = xtp.createRun();
                setCellParagraph(xtp, xr, 14, "仿宋_GB2312", dutytime.get("zbsj").toString());

                //设置行间距
                setLineSpacing(xtp, 600);

                //设置段落
                xtp = xtCell.addParagraph();
                xr = xtp.createRun();
                setCellParagraph(xtp, xr, 14, "仿宋_GB2312", getWeek(Long.parseLong(dutytime.get("DUTYTIME").toString())));
                //设置行间距
                setLineSpacing(xtp, 600);
                //设置表格列宽度
                cttcPr = xtCell.getCTTc().addNewTcPr();
                ctTblWidth = cttcPr.addNewTcW();
                setCellWidth(ctTblWidth, 11100 / result.size());

            }

            for (int i = 0; i < result.get(0).size(); i++) {

                Map<String, Object> bmMap = result.get(0).get(i);

                XWPFTableRow xwpfTableRow = infoTable.createRow();
                xtCell = xwpfTableRow.getCell(0);
                xpList = xtCell.getParagraphs();//因为有一个空白行,这两句话是删除空白行
                xtCell.removeParagraph(xpList.size() - 1);
                //设置段落
                xtp = xtCell.addParagraph();
                xr = xtp.createRun();
                setCellParagraph(xtp, xr, 14, "仿宋_GB2312", bmMap.get("BMMC") == null ? "" : bmMap.get("BMMC") + "");

                //设置表格宽度
                cttcPr = xtCell.getCTTc().addNewTcPr();
                ctTblWidth = cttcPr.addNewTcW();
                setCellWidth(ctTblWidth, 2500);

                for (int z = 0; z < result.size(); z++) {
                    Map<String, Object> map = result.get(z).get(i);

                    xtCell = xwpfTableRow.getCell(z + 1);
                    xpList = xtCell.getParagraphs();//因为有一个空白行,这两句话是删除空白行
                    xtCell.removeParagraph(xpList.size() - 1);
                    //设置段落
                    xtp = xtCell.addParagraph();
                    xr = xtp.createRun();
                    setCellParagraph(xtp, xr, 14, "仿宋_GB2312", map.get("PERSONS") == null ? "" : map.get("PERSONS") + "");
                    //设置表格列宽度
                    cttcPr = xtCell.getCTTc().addNewTcPr();
                    ctTblWidth = cttcPr.addNewTcW();
                    setCellWidth(ctTblWidth, 11100 / result.size());
                }
            }
        }

    }

    OutputStream outStream = null;
    try {
        outStream = response.getOutputStream();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    response.reset();
    try {
        response.setHeader("Content-disposition", "attachment; filename=" + new String((title + ".docx").getBytes("gb2312"), "ISO8859-1"));
        response.setContentType("application/msword");
        xwpfDocument.write(outStream);
        if (outStream != null) {
            outStream.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

//获取星期
public String getWeek(Long time) {
    Date date = new Date(time);
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    String[] weeks = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
    int weekIndex = cal.get(Calendar.DAY_OF_WEEK) - 1;
    if (weekIndex < 0) {
        weekIndex = 0;
    }
    return weeks[weekIndex];
}

//设置段落
public void setCellParagraph(XWPFParagraph xtp, XWPFRun xr, int fontSize, String fontFamily, String value) {
    xtp.setVerticalAlignment(TextAlignment.CENTER);
    xtp.setAlignment(ParagraphAlignment.CENTER);
    xr.setFontSize(fontSize);
    xr.setFontFamily(fontFamily);
    xr.setText(value);
}

//设置表格列宽度
public void setCellWidth(CTTblWidth ctTblWidth, long cWidth) {
    ctTblWidth.setType(STTblWidth.DXA);
    ctTblWidth.setW(BigInteger.valueOf(cWidth));
}

//设置页面布局
public void setParperLayout(CTSectPr ctSectPr, XWPFTable infoTable, long pgSzWidth, long pgSzHeight, STPageOrientation.Enum orinet, long pgMarLeft, long pgMarTop, long pgMarRight, long pgMarBottom, long tableWidth) {
    //设置页面为A4
    CTPageSz ctPageSz = ctSectPr.getPgSz();
    ctPageSz.setW(BigInteger.valueOf(pgSzWidth));
    ctPageSz.setH(BigInteger.valueOf(pgSzHeight));

    //设置打印方向  PORTRAIT  竖向   LANDSCAPE  横向
    ctPageSz.setOrient(orinet);
    //设置页面边距
    if (!ctSectPr.isSetPgMar()) {
        ctSectPr.addNewPgMar();
    }
    //设置页边距,word中一厘米等于567
    CTPageMar ctPageMar = ctSectPr.getPgMar();
    ctPageMar.setLeft(BigInteger.valueOf(pgMarLeft));
    ctPageMar.setTop(BigInteger.valueOf(pgMarTop));
    ctPageMar.setRight(BigInteger.valueOf(pgMarRight));
    ctPageMar.setBottom(BigInteger.valueOf(pgMarBottom));

    //列宽自动分割
    CTTblPr ctTblPr = infoTable.getCTTbl().addNewTblPr();
    CTTblWidth ctTblWidth = ctTblPr.addNewTblW();
    ctTblWidth.setType(STTblWidth.DXA);
    ctTblWidth.setW(BigInteger.valueOf(tableWidth));

    //设置布局为固定不变方式
    CTTblLayoutType ctTblLayoutType = ctTblPr.isSetTblLayout() ? ctTblPr.getTblLayout() : ctTblPr.addNewTblLayout();
    ctTblLayoutType.setType(STTblLayoutType.FIXED);
}

//设置行间距
public static void setLineSpacing(XWPFParagraph paragraph, int size) {
    CTP ctp = paragraph.getCTP();
    CTPPr ppr = ctp.isSetPPr() ? ctp.getPPr() : ctp.addNewPPr();
    CTSpacing spacing = ppr.isSetSpacing() ? ppr.getSpacing() : ppr.addNewSpacing();
    spacing.setAfter(BigInteger.valueOf(0));
    spacing.setBefore(BigInteger.valueOf(0));
    //设置行距类型为 EXACT
    spacing.setLineRule(STLineSpacingRule.EXACT);
    //1磅数是20
    spacing.setLine(BigInteger.valueOf(size));
}