1. 程式人生 > >java實現的匯出word文件

java實現的匯出word文件

之前沒有做過類似的功能,所以第一次接觸的時候費了我一天的時間來完成這個功能。先說一下原理,其實就是通過修改後綴來完成的。

需要先用office2013做一個word模板,就是你想要生成的word的模板,儲存為xml格式。然後線上格式化一下,這樣生成的程式碼比較規範,然後將字尾修改為ftl,內容為一下格式:、

我使用的方法是通過Action跳轉的方法來進行呼叫的,Action方法如下,

public String exportProWorkOrder(){
			
			/** 取出 引數**/
			
			/** 輸出審批  **/
			Template t=null;
	        PrintWriter wt = null;
	        
			try { 
				/** 查詢資料 **/
				ProjectWorkOrder pwo = consultingProjectBo.findPWOMessage(18);
				
				Map<String,Object> dataMap=new HashMap<String,Object>();
			    
	            //getData(dataMap);  
			    /** 放置資料 **/
				consultingProjectBo.makeExportProWorkOrderData(pwo,dataMap); 
			    String fn = makeFileName(pwo);
			    
	            //FTL檔案所存在的位置  
			    	t = freeMarkerConfiguration.getTemplate("export_proworkorder.ftl"); //檔名  
	            
	            
	            //配置 Response 引數
	    		getResponse().setContentType(
	    				"application/msword; charset=UTF-8");
	            getResponse().setHeader(
						"Content-Disposition",
						"Attachment;filename= "
								+ new String(fn.toString().getBytes(
										//"UTF-8"),"UTF-8"));
										"gb2312"), "ISO8859_1"));//20151030 改為UTF-8 需要相容性測試
				wt = getResponse().getWriter();
				t.process(dataMap, wt);
				
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        } finally {
	        	if(wt!=null){
	        		wt.flush();
	            	wt.close();	
	        	}
	        }
			return null;
		}
	
	protected String makeFileName(ProjectWorkOrder pwo) {
		if(pwo==null){
			return "檔案不存在";
		}
		
		String filename = "";
		if(pwo.getProjectTitle()!=null){
			filename = pwo.getProjectTitle() + "工程造價諮詢專案工作交辦單" + ".doc";
		}else{
			filename = "工程造價諮詢專案工作交辦單"+".doc";
		}
		
		return filename;
	}

跳轉進入方法中,期中放置資料的方法如下,
public ProjectWorkOrder findPWOMessage(Integer projectId){
		SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ); 
		Project project = null;
		List<ProjectDepartment> list = null;
		ProjectEngineering pe = null;
		project = projectBo.findFull(projectId);
		list = projectDepartmentBo.findPDByProjectId(projectId);
		pe = projectEngineeringBo.findPEByProjectId(projectId);
		ProjectWorkOrder pwo = new ProjectWorkOrder();
		  if(projectId != null){
		     pwo.setProjectId(projectId);
		  }
		  if(project.getProject_title() != null){
		     pwo.setProjectTitle(project.getProject_title());
		  }
		  if(project.getBegin_date() != null){
		     pwo.setBeginDate(sdf.format(project.getBegin_date()));
		  }
		  if(project.getEnd_date() != null){
		     pwo.setEndDate(sdf.format(project.getEnd_date()));
		  }
		  if(project.getProject_target() != null){
		     pwo.setProjecTarget(project.getProject_target());
		  }
		  if(project.getMember_id() != null){
			  Member member = memberBo.getCacheMember(project.getMember_id());
		     pwo.setMemberId(member.getMember_name());
		  }
		  if(pe.getPlan_no() != null){
		     pwo.setPlanNu(pe.getPlan_no());
		  }
		  if(pe.getIncrement() != null){
		     pwo.setInvestment(pe.getIncrement());
		  }
		  if(pe.getDo_item() != null){
		     pwo.setDoItem(pe.getDo_item());
		  }
		  if(pe.getKey_point() != null){
		     pwo.setKeyPoint(pe.getKey_point());
		  }
		  if(list != null){
		     pwo.setChild(addtypePlus(list));
		  }
		return pwo;
	}
	/**
	 *將工程造價諮詢專案工作交辦單匯出為word 
	 */
	@Override
	public void makeExportProWorkOrderData(ProjectWorkOrder pwo, Map<String, Object> dataMap) {
			if(pwo==null){
				return;
			}
			if(pwo.getProjectTitle() != null){
			     dataMap.put("ptitle",pwo.getProjectTitle());//專案名稱
			}else{
				 dataMap.put("ptitle","無");
			}
			if(pwo.getProjectId() != null){
				 dataMap.put("pid", pwo.getProjectId());//工程id
			}else{
				 dataMap.put("pid", "0");
			}
			if(pwo.getBeginDate() != null){
				 dataMap.put("begindate", pwo.getBeginDate());//專案開始時間
			}else{
				 dataMap.put("begindate", "無");
			}
			if(pwo.getEndDate() != null){
				 dataMap.put("endate", pwo.getEndDate());//結束日期
			}else{
				 dataMap.put("endate", "無");
			}
			if(pwo.getProjecTarget() != null){
				 dataMap.put("ptarget", pwo.getProjecTarget());//目標
			}else{
				 dataMap.put("ptarget", "無");
			}
			if(pwo.getMemberId() != null){
				 dataMap.put("pmemberid", pwo.getMemberId());//負責人
			}else{
				 dataMap.put("pmemberid", "無");
			}
			if(pwo.getPlanNu() != null){
				 dataMap.put("plano", pwo.getPlanNu());//計劃編號
			}else{
				 dataMap.put("plano", "無");
			}if(pwo.getInvestment() != null){
				 dataMap.put("investment", pwo.getInvestment());//總投資
			}else{
				 dataMap.put("investment", "無");
			}
			if(pwo.getDoItem() != null){
				 dataMap.put("doitem", pwo.getDoItem());//事項
			}else{
				 dataMap.put("doitem", "無");
			}
			if(pwo.getKeyPoint() != null){
				 dataMap.put("keypoint", pwo.getKeyPoint());//重點
			}else{
				 dataMap.put("keypoint", "無");
			}
			if(pwo.getChild() != null){
				 dataMap.put("list", pwo.getChild());//聯絡人列表
			}else{
				 dataMap.put("list", "無");
			}
			SimpleDateFormat tempDate = new SimpleDateFormat("yyyy年MM月dd日");    
			String datetime = tempDate.format(DateTimeUtil.getCurrDate());    
			dataMap.put("datetime", datetime);
	}
	/**
	 * 將單位型別數字轉換為對應的字元
	 */
	private List<ProjectDepartment> addtypePlus(List<ProjectDepartment> list){
		for (ProjectDepartment projectDepartment : list) {
			if(projectDepartment.getType() == 1){projectDepartment.setTypePlus("委託單位");}
			if(projectDepartment.getType() == 2){projectDepartment.setTypePlus("建設單位");}
			if(projectDepartment.getType() == 3){projectDepartment.setTypePlus("施工單位");}
			if(projectDepartment.getType() == 4){projectDepartment.setTypePlus("監理單位");}
			if(projectDepartment.getType() == 5){projectDepartment.setTypePlus("設計單位");}
			if(projectDepartment.getType() == 6){projectDepartment.setTypePlus("編制單位");}
		}
		return list;
	}

配置檔案的資訊這裡就不在多說了,同時需要修改ftl中的引數,修改方法如下,

 <w:r wsp:rsidRPr="002C3578">
                <w:rPr>
                  <w:rFonts w:ascii="宋體" w:h-ansi="宋體" w:hint="fareast"/>
                  <wx:font wx:val="宋體"/>
                  <w:sz-cs w:val="21"/>
                </w:rPr>
                <w:t><![CDATA[${doitem}]]></w:t>
              </w:r>

與jsp中的方法基本一致,

處理list,

如果遇到迴圈的話,使用如下的方法,

<#list list as bean><!-- Start 迴圈體 -->
        <w:tr wsp:rsidR="002C3578" wsp:rsidRPr="002C3578" wsp:rsidTr="002C3578">
          <w:trPr>
            <w:trHeight w:val="427"/>
          </w:trPr>
          <w:tc>
            <w:tcPr>
              <w:tcW w:w="534" w:type="dxa"/>
              <w:vmerge/>
              <w:shd w:val="clear" w:color="auto" w:fill="auto"/>
            </w:tcPr>
            <w:p wsp:rsidR="0068277C" wsp:rsidRPr="002C3578" wsp:rsidRDefault="0068277C" wsp:rsidP="002C3578">
              <w:pPr>
                <w:jc w:val="center"/>
                <w:rPr>
                  <w:rFonts w:ascii="宋體" w:h-ansi="宋體" w:hint="fareast"/>
                  <wx:font wx:val="宋體"/>
                  <w:sz-cs w:val="21"/>
                </w:rPr>
              </w:pPr>
            </w:p>
          </w:tc>
          <w:tc>
            <w:tcPr>
              <w:tcW w:w="1596" w:type="dxa"/>
              <w:shd w:val="clear" w:color="auto" w:fill="auto"/>
            </w:tcPr>
            <w:p wsp:rsidR="0068277C" wsp:rsidRPr="002C3578" wsp:rsidRDefault="0068277C" wsp:rsidP="002C3578">
              <w:pPr>
                <w:spacing w:line="360" w:line-rule="auto"/>
                <w:jc w:val="center"/>
                <w:rPr>
                  <w:rFonts w:ascii="宋體" w:h-ansi="宋體" w:hint="fareast"/>
                  <wx:font wx:val="宋體"/>
                  <w:sz-cs w:val="21"/>
                </w:rPr>
              </w:pPr>
              <w:r wsp:rsidRPr="002C3578">
                <w:rPr>
                  <w:rFonts w:ascii="宋體" w:h-ansi="宋體" w:hint="fareast"/>
                  <wx:font wx:val="宋體"/>
                  <w:sz-cs w:val="21"/>
                </w:rPr>
                <w:t><![CDATA[${bean.typePlus}]]></w:t>
              </w:r>
            </w:p>
          </w:tc>
          <w:tc>
            <w:tcPr>
              <w:tcW w:w="2130" w:type="dxa"/>
              <w:shd w:val="clear" w:color="auto" w:fill="auto"/>
            </w:tcPr>
            <w:p wsp:rsidR="0068277C" wsp:rsidRPr="002C3578" wsp:rsidRDefault="0068277C" wsp:rsidP="002C3578">
              <w:pPr>
                <w:spacing w:line="360" w:line-rule="auto"/>
                <w:jc w:val="center"/>
                <w:rPr>
                  <w:rFonts w:ascii="宋體" w:h-ansi="宋體" w:hint="fareast"/>
                  <wx:font wx:val="宋體"/>
                  <w:sz-cs w:val="21"/>
                </w:rPr>
              </w:pPr>
              <w:r wsp:rsidRPr="002C3578">
                <w:rPr>
                  <w:rFonts w:ascii="宋體" w:h-ansi="宋體" w:hint="fareast"/>
                  <wx:font wx:val="宋體"/>
                  <w:sz-cs w:val="21"/>
                </w:rPr>
                <w:t><![CDATA[${bean.department_name}]]></w:t>
              </w:r>
            </w:p>
          </w:tc>
          <w:tc>
            <w:tcPr>
              <w:tcW w:w="2131" w:type="dxa"/>
              <w:shd w:val="clear" w:color="auto" w:fill="auto"/>
            </w:tcPr>
            <w:p wsp:rsidR="0068277C" wsp:rsidRPr="002C3578" wsp:rsidRDefault="0068277C" wsp:rsidP="002C3578">
              <w:pPr>
                <w:spacing w:line="360" w:line-rule="auto"/>
                <w:jc w:val="center"/>
                <w:rPr>
                  <w:rFonts w:ascii="宋體" w:h-ansi="宋體" w:hint="fareast"/>
                  <wx:font wx:val="宋體"/>
                  <w:sz-cs w:val="21"/>
                </w:rPr>
              </w:pPr>
              <w:r wsp:rsidRPr="002C3578">
                <w:rPr>
                  <w:rFonts w:ascii="宋體" w:h-ansi="宋體" w:hint="fareast"/>
                  <wx:font wx:val="宋體"/>
                  <w:sz-cs w:val="21"/>
                </w:rPr>
                <w:t><![CDATA[${bean.linkman}]]></w:t>
              </w:r>
            </w:p>
          </w:tc>
          <w:tc>
            <w:tcPr>
              <w:tcW w:w="2131" w:type="dxa"/>
              <w:shd w:val="clear" w:color="auto" w:fill="auto"/>
            </w:tcPr>
            <w:p wsp:rsidR="0068277C" wsp:rsidRPr="002C3578" wsp:rsidRDefault="0068277C" wsp:rsidP="002C3578">
              <w:pPr>
                <w:spacing w:line="360" w:line-rule="auto"/>
                <w:jc w:val="center"/>
                <w:rPr>
                  <w:rFonts w:ascii="宋體" w:h-ansi="宋體" w:hint="fareast"/>
                  <wx:font wx:val="宋體"/>
                  <w:sz-cs w:val="21"/>
                </w:rPr>
              </w:pPr>
              <w:r wsp:rsidRPr="002C3578">
                <w:rPr>
                  <w:rFonts w:ascii="宋體" w:h-ansi="宋體"/>
                  <wx:font wx:val="宋體"/>
                  <w:sz-cs w:val="21"/>
                </w:rPr>
                <w:t><![CDATA[${bean.phone}]]></w:t>
              </w:r>
            </w:p>
          </w:tc>
        </w:tr>
        </#list><!-- End 迴圈體 -->

這樣就能匯出想要的word文件,一定要記住,使用office2013,我試著用WPS,但是生成內容讓我很懵逼,全是xml程式碼。可能思路不太清晰。。。