1.1 实例1
在使用POI写word doc文件的时候我们必须要先有一个doc文件才行,因为我们在写doc文件的时候是通过HWPFDocument来写的,而HWPFDocument是要依附于一个doc文件的。所以通常的做法是我们先在硬盘上准备好一个内容空白的doc文件,然后建立一个基于该空白文件的HWPFDocument。之后我们就可以往HWPFDocument里面新增内容了,然后再把它写入到另外一个doc文件中,这样就相当于我们使用POI生成了word doc文件。
在实际应用中,我们在生成word文件的时候都是生成某一类文件,该类文件的格式是固定的,只是某些字段不一样罢了。所以在实际应用中,我们大可不必将整个word文件的内容都通过HWPFDocument生成。而是先在磁盘上新建一个word文档,其内容就是我们需要生成的word文件的内容,然后把里面一些属于变量的内容使用类似于“${paramName}”这样的方式代替。这样我们在基于某些信息生成word文件的时候,只需要获取基于该word文件的HWPFDocument,然后调用Range的replaceText()方法把对应的变量替换为对应的值即可,之后再把当前的HWPFDocument写入到新的输出流中。这种方式在实际应用中用的比较多,因为它不但可以减少我们的工作量,还可以让文本的格式更加的清晰。下面我们就来基于这种方式做一个示例。
假设我们现在拥有一些变动的信息,然后需要通过这些信息生成如下格式的
word doc
文件:
那么根据上面的描述,首先第一步,我们建立一个对应格式的doc文件作为模板,其内容是这样的:
有了这样一个模板之后,我们就可以建立对应的HWPFDocument,然后替换对应的变量为相应的值,再把HWPFDocument输出到对应的输出流即可。下面是对应的代码。
public class HwpfTest {
@Test
public void testWrite() throws Exception {
String templatePath = "D:\\word\\template.doc";
InputStream is = new FileInputStream(templatePath);
HWPFDocument doc = new HWPFDocument(is);
Range range = doc.getRange();
//把range范围内的${reportDate}替换为当前的日期
range.replaceText("${reportDate}", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
range.replaceText("${appleAmt}", "100.00");
range.replaceText("${bananaAmt}", "200.00");
range.replaceText("${totalAmt}", "300.00");
OutputStream os = new FileOutputStream("D:\\word\\write.doc");
//把doc输出到输出流中
doc.write(os);
this.closeStream(os);
this.closeStream(is);
}
/**
* 关闭输入流
* @param is
*/
private void closeStream(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 关闭输出流
* @param os
*/
private void closeStream(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1.2 实例2
需要的jar包:poi-3.10.1.jar;poi-ooxml-3.10.1.jar;poi-ooxml-schemas-3.10.1.jar;poi-scratchpad-3.10.1.jar
* POI方式导出word文档,需要提前创建word导出模板
* POI方式导出word时,本机安装的office版本是2007以前的版本,使用到的是HWPFDocument
* POI方式导出word时,本机安装的office版本是2007+的版本,使用到的是XWPFDocument
package officeWordDoc;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
/**
* @ClassName:WordDocDemo_POI
* @Description:使用POI方式实现word文档导出功能
* 需要的jar包:poi-3.10.1.jar;poi-ooxml-3.10.1.jar;
* poi-ooxml-schemas-3.10.1.jar;poi-scratchpad-3.10.1.jar
* POI方式导出word文档,需要提前创建word导出模板
* POI方式导出word时,本机安装的office版本是2007以前的版本,使用到的是HWPFDocument
* POI方式导出word时,本机安装的office版本是2007+的版本,使用到的是XWPFDocument
* @date:2017年5月12日
* 修改备注:
*/
public class WordDocDemo_POI{
public static void main(String[] args){
WordDocDemo_POI poi = new WordDocDemo_POI();
poi.exportWord();
}
/**
* @Description:使用POI实现word导出功能,JSF页面请求,此处涉及到JSF框架中FacesContext对象,可摘除,
* @date: 2017年5月12日 下午6:50:51
* @修改备注:
*/
public void exportWord() {
FacesContext context = FacesContext.getCurrentInstance();
context.responseComplete();
HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
response.reset();
try {
String fileName = "关于"+"eventInfo.getEventName()"+"的情况报告.doc";
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-disposition", "attachment;filename="+fileName);
response.setContentType("application/msword");
ServletOutputStream outputStream = response.getOutputStream();
//引入word模板,转化成流
//String wordTemp = "E:\\项目\\导出报告模板\\reportTemplate.doc";
String wordTemp = request.getSession().getServletContext().getRealPath("eventInfo.export.reportTemplate");
FileInputStream inputStream = new FileInputStream(wordTemp);
HWPFDocument document = new HWPFDocument(inputStream);
//替换内容
Range range = document.getRange();
Map<String, String> content = this.getReplaceContent();
for(java.util.Map.Entry<String, String> entry : content.entrySet()){
range.replaceText(entry.getKey(), entry.getValue());
}
document.write(outputStream);
inputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
FacesContext.getCurrentInstance().responseComplete();
}
/**
* 获取模板中需要替换的文字
* @param report
* @return
*/
private Map<String, String> getReplaceContent(){
Map<String, String> content = new HashMap<String, String>();
content.put("${eventType}", "typeName类型名称");
content.put("${reportName}", "report.getReportName报告名称");
content.put("${reporterUnit}", "report.getReporterUnit报送单位");
content.put("${loginUser}", "loginUser登录人员信息");
content.put("${nowTime}", "yyyy年MM月dd日时间消息");
content.put("${occurTime}", "yyyy年MM月dd日事发时间");
content.put("${disaster}", "非必填写1");
content.put("${eventDesc}", "非必填写2");
content.put("${eventDesc}", "非必填写3");
return content;
}
}
1.3 实例3
public void exportApplyForm() throws Exception {
String id = request.getParameter("id");
applyForm = applyFormService.retriveById(id);
Map<String, Object> params = new HashMap<String, Object>();
params.put("${name}", applyForm.getName());
params.put("${sex}", applyForm.getSex());
params.put("${political}", applyForm.getPolitical());
params.put("${place}", applyForm.getPlace());
params.put("${classes}", applyForm.getClasses());
params.put("${id}", applyForm.getStudentId());
params.put("${qq}", applyForm.getQq());
params.put("${tel}", applyForm.getTel());
params.put("${oldJob}", applyForm.getOldJob());
params.put("${swap}", applyForm.getSwap());
params.put("${first}", applyForm.getFirst());
params.put("${second}", applyForm.getSecond());
params.put("${award}", applyForm.getAward());
params.put("${achievement}", applyForm.getAchievement());
params.put("${advice}", applyForm.getAdvice());
params.put("${attach}", applyForm.getAttach());
XwpfTUtil xwpfTUtil = new XwpfTUtil();
XWPFDocument doc;
String fileNameInResource = "sta.docx";
InputStream is;
/*is = new FileInputStream(filePath);*/
is = getClass().getClassLoader().getResourceAsStream(fileNameInResource);
doc = new XWPFDocument(is);
xwpfTUtil.replaceInPara(doc, params);
//替换表格里面的变量
xwpfTUtil.replaceInTable(doc, params);
OutputStream os = response.getOutputStream();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition","attachment;filename="+applyForm.getName()+".docx");
doc.write(os);
xwpfTUtil.close(os);
xwpfTUtil.close(is);
os.flush();
os.close();
}