LBL121520 2016-04-29 03:09 采纳率: 100%
浏览 2324
已采纳

怎么用java实现doc文档模板插入数据和表格并导出?急急急,在线等

我要实现一个模板导出功能,模板包含标题和文字内容,模板中间还有一个表格,和结尾文字。
要实现动态添加标题文字,其中表格中内容部分动态添加数据,可能会有多种模板,区别是表格样子不同,都要添加内容,最后整个导出doc文件。有没有demo?各位大神?谢谢了先。
下面图片中红色框住部分是要动态添加数据的地方,其他地方是模板原型。

图片说明

  • 写回答

5条回答

  • LBL121520 2016-05-03 07:20
    关注

    下面是我实现的方式,用poi工具。

     /**
         * 
         * @param filePath 源文件位置+文件名
         * @param request 请求
         * @param twelveList 填充数据
         * @param uname 导出用户
         */
        public String insertDataToTable(List<Map<String, Object>> explist,HttpServletRequest request,
                List<Map<String, Object>> twelveList,String uname) throws Exception {
            String filePath=PropertiesUtil.getValue("exportmouldPath")+explist.get(0).get("MODULE_URL").toString();//文件源路径
            String desktopPaths =this.returnWebUrl(request);
            desktopPaths=desktopPaths+"/"+PropertiesUtil.getValue("exportybPath");//保存文件路径
            String fend=filePath.substring(filePath.indexOf(".do"), filePath.length());
            String fname=DateUtil.getNowTimestamp().getTime()+"_exp"+fend;//返回文件
            InputStream is = new FileInputStream(filePath);//文件源
            XWPFDocument doc = new XWPFDocument(is);
            insertValueToTable(doc, twelveList,3,true,uname);//写入数据
            saveDocument(doc, desktopPaths+fname); 
            return fname;
        }
        //获取项目路径根目录
        public String returnWebUrl(HttpServletRequest request) throws Exception {
            String urlweb=getClass().getResource("/").getFile().toString() ;
            urlweb=urlweb.substring(0,urlweb.indexOf(request.getContextPath())+request.getContextPath().length());
            return urlweb;
    
        }
    
        /**
         * @Description: 按模版行样式填充数据,暂未实现特殊样式填充(如列合并),只能用于普通样式(如段落间距 缩进 字体 对齐)
         * @param resultList 填充数据
         * @param tableRowSize 模版表格行数 取第一个行数相等列数相等的表格填充
         * @param isDelTmpRow 是否删除模版行
         */
        public void insertValueToTable(XWPFDocument doc,List<Map<String,Object>> rlist,
                int tableRowSize,boolean isDelTmpRow,String uname) throws Exception {
            List<Map<String,Object>> resultList=this.getOneDayTable(rlist);//数据替换成模板需要的数据格式(略)
            Map<String, String>map=new HashMap<String, String>();
            map.put("${city}", rlist.get(0).get("CITY_NAME").toString());
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日");
            map.put("${user}", uname);
            map.put("${date}", sdf.format(new Date()));
            Iterator<XWPFTable> iterator = doc.getTablesIterator();
            XWPFTable table = null;
            List<XWPFTableRow> rows=null;
            List<XWPFTableCell> cells=null;
            List<XWPFTableCell> tmpCells=null;//模版列
            XWPFTableRow tmpRow=null;//匹配用
            XWPFTableCell tmpCell=null;//匹配用
            boolean flag=false;//是否找到表格
            while (iterator.hasNext()) {
                table = iterator.next();
                rows = table.getRows();
                if(rows.size()==tableRowSize){
                    tmpRow=rows.get(tableRowSize-1);
                    cells =tmpRow.getTableCells();
                    if(cells.size()==resultList.get(0).size()){
                        flag=true;
                        break;
                    }
                }
            }
            if(!flag){
                return;
            }
            tmpCells=tmpRow.getTableCells();
             // 替换段落中的指定文字  city   ${city}
            Iterator<XWPFParagraph> itPara = doc.getParagraphsIterator();  
            while (itPara.hasNext()) {  
                XWPFParagraph paragraph = (XWPFParagraph) itPara.next();  
                List<XWPFRun> runs = paragraph.getRuns();  
                for (int i = 0; i < runs.size(); i++) {  
                    String oneparaString = runs.get(i).getText(  
                            runs.get(i).getTextPosition());  
                    if(oneparaString==null||"".equals(oneparaString)||oneparaString.length()<1){
                    }else{
                        oneparaString = oneparaString.replace("${city}", map.get("${city}"));  
                        oneparaString = oneparaString.replace("${user}", map.get("${user}"));  
                        oneparaString = oneparaString.replace("${date}", map.get("${date}"));  
                    }
                    runs.get(i).setText(oneparaString, 0);  
                }  
            } 
            //写数据
            for(int i=0,len=resultList.size();i<len;i++){
                XWPFTableRow row=table.createRow();
                row.setHeight(tmpRow.getHeight());
                Map<String,Object> list=resultList.get(i);
                cells=row.getTableCells();
    
                //插入的行会填充与表格第一行相同的列数
                for(int k=0,klen=cells.size();k<klen;k++){
                    tmpCell=tmpCells.get(k);
                    XWPFTableCell cell=cells.get(k);
                    setCellText(tmpCell, cell, list.get("k"+k).toString());
                }
                //继续写剩余的列
                for(int j=cells.size(),jlen=list.size();j<jlen;j++){
                    tmpCell=tmpCells.get(j);
                    XWPFTableCell cell=row.addNewTableCell();
                    setCellText(tmpCell, cell, list.get("k"+(j)).toString());
                }
            }
            //删除模版行
            if(isDelTmpRow){
                table.removeRow(tableRowSize-1);
            }
        }
    
        public  void setCellText(XWPFTableCell tmpCell,XWPFTableCell cell,String text) throws Exception{
            CTTc cttc2 = tmpCell.getCTTc();
            CTTcPr ctPr2=cttc2.getTcPr();
    
            CTTc cttc = cell.getCTTc();
            CTTcPr ctPr = cttc.addNewTcPr();
            cell.setColor(tmpCell.getColor());
    //      cell.setVerticalAlignment(tmpCell.getVerticalAlignment());
            if(ctPr2.getTcW()!=null){
                ctPr.addNewTcW().setW(ctPr2.getTcW().getW());
            }
            if(ctPr2.getVAlign()!=null){
                ctPr.addNewVAlign().setVal(ctPr2.getVAlign().getVal());
            }
            if(cttc2.getPList().size()>0){
                CTP ctp=cttc2.getPList().get(0);
                if(ctp.getPPr()!=null){
                    if(ctp.getPPr().getJc()!=null){
                        cttc.getPList().get(0).addNewPPr().addNewJc().setVal(ctp.getPPr().getJc().getVal());
                    }
                }
            }
    
            if(ctPr2.getTcBorders()!=null){
                ctPr.setTcBorders(ctPr2.getTcBorders());
            }
    
            XWPFParagraph tmpP=tmpCell.getParagraphs().get(0);
            XWPFParagraph cellP=cell.getParagraphs().get(0);
            XWPFRun tmpR =null;
            if(tmpP.getRuns()!=null&&tmpP.getRuns().size()>0){
                tmpR=tmpP.getRuns().get(0);
            }
            XWPFRun cellR = cellP.createRun();
            cellR.setText(text);
            //复制字体信息
            if(tmpR!=null){
                cellR.setBold(tmpR.isBold());
                cellR.setItalic(tmpR.isItalic());
                cellR.setStrike(tmpR.isStrike());
                cellR.setUnderline(tmpR.getUnderline());
                cellR.setColor(tmpR.getColor());
                cellR.setTextPosition(tmpR.getTextPosition());
                if(tmpR.getFontSize()!=-1){
                    cellR.setFontSize(tmpR.getFontSize());
                }
                if(tmpR.getFontFamily()!=null){
                    cellR.setFontFamily(tmpR.getFontFamily());
                }
                if(tmpR.getCTR()!=null){
                    if(tmpR.getCTR().isSetRPr()){
                        CTRPr tmpRPr =tmpR.getCTR().getRPr();
                        if(tmpRPr.isSetRFonts()){
                            CTFonts tmpFonts=tmpRPr.getRFonts();
                            CTRPr cellRPr=cellR.getCTR().isSetRPr() ? cellR.getCTR().getRPr() : cellR.getCTR().addNewRPr();
                            CTFonts cellFonts = cellRPr.isSetRFonts() ? cellRPr.getRFonts() : cellRPr.addNewRFonts();
                            cellFonts.setAscii(tmpFonts.getAscii());
                            cellFonts.setAsciiTheme(tmpFonts.getAsciiTheme());
                            cellFonts.setCs(tmpFonts.getCs());
                            cellFonts.setCstheme(tmpFonts.getCstheme());
                            cellFonts.setEastAsia(tmpFonts.getEastAsia());
                            cellFonts.setEastAsiaTheme(tmpFonts.getEastAsiaTheme());
                            cellFonts.setHAnsi(tmpFonts.getHAnsi());
                            cellFonts.setHAnsiTheme(tmpFonts.getHAnsiTheme());
                        }
                    }
                }
            }
            //复制段落信息
            cellP.setAlignment(tmpP.getAlignment());
    //      cellP.setVerticalAlignment(tmpP.getVerticalAlignment());
            cellP.setBorderBetween(tmpP.getBorderBetween()); 
            cellP.setBorderBottom(tmpP.getBorderBottom());
            cellP.setBorderLeft(tmpP.getBorderLeft());
            cellP.setBorderRight(tmpP.getBorderRight());
            cellP.setBorderTop(tmpP.getBorderTop());
            cellP.setPageBreak(tmpP.isPageBreak());
            if(tmpP.getCTP()!=null){
                if(tmpP.getCTP().getPPr()!=null){
                    CTPPr tmpPPr = tmpP.getCTP().getPPr();
                    CTPPr cellPPr = cellP.getCTP().getPPr() != null ? cellP.getCTP().getPPr() : cellP.getCTP().addNewPPr();
                    //复制段落间距信息
                    CTSpacing tmpSpacing =tmpPPr.getSpacing();
                    if(tmpSpacing!=null){
                        CTSpacing cellSpacing= cellPPr.getSpacing()!=null?cellPPr.getSpacing():cellPPr.addNewSpacing();
                        if(tmpSpacing.getAfter()!=null){
                            cellSpacing.setAfter(tmpSpacing.getAfter());
                        }
                        if(tmpSpacing.getAfterAutospacing()!=null){
                            cellSpacing.setAfterAutospacing(tmpSpacing.getAfterAutospacing());
                        }
                        if(tmpSpacing.getAfterLines()!=null){
                            cellSpacing.setAfterLines(tmpSpacing.getAfterLines());
                        }
                        if(tmpSpacing.getBefore()!=null){
                            cellSpacing.setBefore(tmpSpacing.getBefore());
                        }
                        if(tmpSpacing.getBeforeAutospacing()!=null){
                            cellSpacing.setBeforeAutospacing(tmpSpacing.getBeforeAutospacing());
                        }
                        if(tmpSpacing.getBeforeLines()!=null){
                            cellSpacing.setBeforeLines(tmpSpacing.getBeforeLines());
                        }
                        if(tmpSpacing.getLine()!=null){
                            cellSpacing.setLine(tmpSpacing.getLine());
                        }
                        if(tmpSpacing.getLineRule()!=null){
                            cellSpacing.setLineRule(tmpSpacing.getLineRule());
                        }
                    }
                    //复制段落缩进信息
                    CTInd tmpInd=tmpPPr.getInd();
                    if(tmpInd!=null){
                        CTInd cellInd=cellPPr.getInd()!=null?cellPPr.getInd():cellPPr.addNewInd();
                        if(tmpInd.getFirstLine()!=null){
                            cellInd.setFirstLine(tmpInd.getFirstLine());
                        }
                        if(tmpInd.getFirstLineChars()!=null){
                            cellInd.setFirstLineChars(tmpInd.getFirstLineChars());
                        }
                        if(tmpInd.getHanging()!=null){
                            cellInd.setHanging(tmpInd.getHanging());
                        }
                        if(tmpInd.getHangingChars()!=null){
                            cellInd.setHangingChars(tmpInd.getHangingChars());
                        }
                        if(tmpInd.getLeft()!=null){
                            cellInd.setLeft(tmpInd.getLeft());
                        }
                        if(tmpInd.getLeftChars()!=null){
                            cellInd.setLeftChars(tmpInd.getLeftChars());
                        }
                        if(tmpInd.getRight()!=null){
                            cellInd.setRight(tmpInd.getRight());
                        }
                        if(tmpInd.getRightChars()!=null){
                            cellInd.setRightChars(tmpInd.getRightChars());
                        }
                    }
                }
            }
        }
    
        public void saveDocument(XWPFDocument document,String savePath) throws Exception{
            FileOutputStream fos = new FileOutputStream(savePath);
            document.write(fos);
            fos.close();
            System.out.println(">>>>>>>>>>导出完成!");
        }
        //生成测试数据
        public List<List<String>> generateTestData(int num) {
            List<List<String>> resultList = new ArrayList<List<String>>();
            for (int i = 1; i <= num; i++) {
                List<String> list = new ArrayList<String>();
                list.add("" + i);
                list.add("测试_" + i);
                list.add("测试2_" + i);
                list.add("测试3_" + i);
                list.add("测试4_" + i);
                resultList.add(list);
            }
            return resultList;
        }
        /**
         * 查询该路径下是否已经有该文件,<br>有就返回一个url+new name 否则返回源数据
         * @param url 路径加名字
         * @return
         */
        public String fileIsExists(String url) {
            File file=new File(url);
            if(file.exists()){
                SimpleDateFormat sdf=new SimpleDateFormat("YYYYMMDDHHmmssSSS");
                return url+"_"+sdf.format(new Date())+".docx";
            }else{
                return url;
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏