我的需求是這樣的:
word文檔類型是xml,用文本編輯器打開看到以下代碼(我只拷貝了頭部部分代碼)
java如何能把它轉(zhuǎn)換為word類型的doc文檔,Apache的poi好像只能把word文檔轉(zhuǎn)換成xml、html等格式的,但不能反過來轉(zhuǎn)。請問有沒有解決過這種需求的朋友,先謝謝了!
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<?mso-application progid="Word.Document"?>
<pkg:package xmlns:pkg="http://schemas.microsoft.com/office/2006/xmlPackage">
<pkg:part pkg:name="/_rels/.rels" pkg:contentType="application/vnd.openxmlformats-package.relationships+xml">
<pkg:xmlData>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>
<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties" Target="docProps/custom.xml"/>
</Relationships>
</pkg:xmlData>
</pkg:part>@smilesnake 首先感謝分享代碼,可能是我的問題,沒有把問題描述清楚,我目前就是按照你的思路來做的,但問題是最后給用戶生成的這個doc文檔是xml類型的(另存為的時候能夠看到)并且用戶打開編輯后再去另存的時候就變成了xml為后綴的文檔了,導致后面打不開,所以我的問題是如何能生成word類型的文檔
大致的思路是先用office2003或者2007編輯好word的樣式,然后另存為xml,將xml翻譯為FreeMarker模板,最后用java來解析FreeMarker模板并輸出Doc。經(jīng)測試這樣方式生成的word文檔完全符合office標準,樣式、內(nèi)容控制非常便利,打印也不會變形,生成的文檔和office中編輯文檔完全一樣。
用xml做導出方案。
先創(chuàng)建一個word文檔,按照需求在word中填好一個模板,然后把對應的數(shù)據(jù)換成變量${},然后將文檔保存為xml文檔格式,使用文檔編輯器打開這個xml格式的文檔,去掉多余的xml符號,使用Freemarker讀取這個文檔然后替換掉變量,輸出word文檔即可
需要freemarker jar包
/**
*/
package com.wt.service.download;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
import net.paoding.rose.web.Invocation;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
/**
*/
@Service
public class DownloadService {
private Logger logger = Logger.getLogger(this.getClass());
/**
* downLoad:(文件下載). <br/>
*
* @author wpengfei
* @param inv
* @param fileName
* @param path
* @throws IOException
* @since JDK 1.6
*/
public void downLoad(Invocation inv, String fileName, String path) throws IOException {
File file = new File(path);// 構(gòu)造要下載的文件
if (file.exists()) {
InputStream ins = null;
BufferedInputStream bins = null;
OutputStream outs = null;
BufferedOutputStream bouts = null;
try {
ins = new FileInputStream(path);// 構(gòu)造一個讀取文件的IO流對象
bins = new BufferedInputStream(ins);// 放到緩沖流里面
outs = inv.getResponse().getOutputStream();// 獲取文件輸出IO流
bouts = new BufferedOutputStream(outs);
String path1 = inv.getRequest().getSession().
getServletContext().getRealPath("/WEB-INF/downloads");
logger.info(path1);
inv.getResponse().setContentType("application/x-download");// 設置response內(nèi)容的類型
inv.getResponse().setHeader("Content-disposition",
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));// 設置頭部信息
// inv.getResponse().setContentLength((int)file.length());
int bytesRead = 0;
byte[] buffer = new byte[8192];
// 開始向網(wǎng)絡傳輸文件流
while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
bouts.write(buffer, 0, bytesRead);
}
bouts.flush();// 這里一定要調(diào)用flush()方法
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bouts != null) {
bouts.close();
}
if (outs != null) {
outs.close();
}
if (bins != null) {
bins.close();
}
if (ins != null) {
ins.close();
}
}
} else {
logger.info("導出的文件不存在");
}
}
}
package com.wt.common.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
/**
*/
public class WordUtil {
@SuppressWarnings("rawtypes")
public static String createWord2(Map dataMap, String templateName, String filePath, String fileName) {
try {
// 創(chuàng)建配置實例
Configuration configuration = new Configuration();
// 設置編碼
configuration.setDefaultEncoding("UTF-8");
// ftl模板文件統(tǒng)一放至 com.lun.template 包下面
configuration.setClassForTemplateLoading(WordUtil.class, "\\com\\wt\\common\\util\\");
// 獲取模板
Template template = configuration.getTemplate(templateName);
// 輸出文件
File outFile = new File(filePath + File.separator + fileName);
// 如果輸出目標文件夾不存在,則創(chuàng)建
if (!outFile.getParentFile().exists()) {
outFile.getParentFile().mkdirs();
}
// 將模板和數(shù)據(jù)模型合并生成文件
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
// 生成文件
template.process(dataMap, out);
// 關(guān)閉流
out.flush();
out.close();
return filePath + File.separator + fileName;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package com.wt.controllers.test1;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.wt.common.util.CommonsUtil;
import com.wt.common.util.Constants;
import com.wt.common.util.ResponseObject;
import com.wt.common.util.WordUtil;
import com.wt.service.download.DownloadService;
/**
*/
@Path("/word")
public class WordController {
@Autowired
private DownloadService downloadService;
private String filePath; //文件路徑
// private String fileName; //文件名稱
private String fileOnlyName; //文件唯一名稱
/**
* createWord2:(這里用一句話描述這個方法的作用). <br/>
* localhost:8080/test1/word/createWord2
*
* @author wpengfei
* @param inv
* @return
* @throws IOException
* @since JDK 1.6
*/
@Get("/createWord2")
public String createWord2(Invocation inv) throws IOException {
/** 用于組裝word頁面需要的數(shù)據(jù) */
Map<String, Object> dataMap = new HashMap<String, Object>();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日");
dataMap.put("startTime", sdf.format(new Date()));
dataMap.put("endTime", sdf.format(new Date()));
dataMap.put("count", 1);
dataMap.put("username", "Tom");
dataMap.put("courseName", "物理");
dataMap.put("className", "1班");
dataMap.put("materialName", "體育學");
dataMap.put("materialVer", 1.0);
dataMap.put("teachAim", "諾克爾12421價是否可驕傲了空間阿凡達撿垃圾覅文件附件安防奇偶萬佛諾克爾12421價是否可驕傲了空間阿凡達撿垃圾覅文件附件安防奇偶萬佛諾克爾12421價是否可驕傲了空間阿凡達撿垃圾覅文件附件安防奇偶萬佛諾克爾12421價是否可驕傲了空間阿凡達撿垃圾覅文件附件安防奇偶萬佛諾克爾12421價是否可驕傲了空間阿凡達撿垃圾覅文件附件安防奇偶萬佛");
//文件導出的目標路徑
filePath=Constants.UPLOAD_BASE_FOLD;
StringBuffer sb=new StringBuffer();
sb.append(sdf.format(new Date()));
sb.append("_");
Random r=new Random();
sb.append(r.nextInt(100));
//文件唯一名稱
fileOnlyName = "testDoc11_"+sb+".doc";
/** 生成word */
String result = WordUtil.createWord2(dataMap, "testDoc11.ftl", filePath, fileOnlyName);
if(StringUtils.isNotBlank(result)){
downloadService.downLoad(inv, fileOnlyName, result);
}
return "@";
}
}
這是freemarker生成word文檔的通病,它本質(zhì)上還是一個xml文本,可以看看:http://www.xdocin.com/office....,它的結(jié)果是真正的docx格式
北大青鳥APTECH成立于1999年。依托北京大學優(yōu)質(zhì)雄厚的教育資源和背景,秉承“教育改變生活”的發(fā)展理念,致力于培養(yǎng)中國IT技能型緊缺人才,是大數(shù)據(jù)專業(yè)的國家
達內(nèi)教育集團成立于2002年,是一家由留學海歸創(chuàng)辦的高端職業(yè)教育培訓機構(gòu),是中國一站式人才培養(yǎng)平臺、一站式人才輸送平臺。2014年4月3日在美國成功上市,融資1
北大課工場是北京大學校辦產(chǎn)業(yè)為響應國家深化產(chǎn)教融合/校企合作的政策,積極推進“中國制造2025”,實現(xiàn)中華民族偉大復興的升級產(chǎn)業(yè)鏈。利用北京大學優(yōu)質(zhì)教育資源及背
博為峰,中國職業(yè)人才培訓領(lǐng)域的先行者
曾工作于聯(lián)想擔任系統(tǒng)開發(fā)工程師,曾在博彥科技股份有限公司擔任項目經(jīng)理從事移動互聯(lián)網(wǎng)管理及研發(fā)工作,曾創(chuàng)辦藍懿科技有限責任公司從事總經(jīng)理職務負責iOS教學及管理工作。
浪潮集團項目經(jīng)理。精通Java與.NET 技術(shù), 熟練的跨平臺面向?qū)ο箝_發(fā)經(jīng)驗,技術(shù)功底深厚。 授課風格 授課風格清新自然、條理清晰、主次分明、重點難點突出、引人入勝。
精通HTML5和CSS3;Javascript及主流js庫,具有快速界面開發(fā)的能力,對瀏覽器兼容性、前端性能優(yōu)化等有深入理解。精通網(wǎng)頁制作和網(wǎng)頁游戲開發(fā)。
具有10 年的Java 企業(yè)應用開發(fā)經(jīng)驗。曾經(jīng)歷任德國Software AG 技術(shù)顧問,美國Dachieve 系統(tǒng)架構(gòu)師,美國AngelEngineers Inc. 系統(tǒng)架構(gòu)師。