java简单操作word实例
本文为大家分享了java简单操作word例子,供大家参考,具体内容如下
packageapache.poi;
importjava.io.ByteArrayInputStream;
importjava.io.ByteArrayOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.OutputStream;
importjava.util.HashMap;
importjava.util.Map;
importorg.apache.poi.hwpf.HWPFDocument;
importorg.apache.poi.hwpf.usermodel.Range;
importorg.apache.poi.poifs.filesystem.DirectoryEntry;
importorg.apache.poi.poifs.filesystem.POIFSFileSystem;
publicclassExportDocTest{
publicstaticvoidmain(String[]args){
StringdestFile="D:\\11.doc";
//#####################根据自定义内容导出Word文档#################################################
StringBufferfileCon=newStringBuffer();
fileCon.append("张大炮男317258963215223\n"+
"2011092013073\n"+
"二炮研究成人\n"+
"201300000120130708");
fileCon.append("\n\r\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
newExportDocTest().exportDoc(destFile,fileCon.toString());
//##################根据Word模板导出单个Word文档###################################################
Map<String,String>map=newHashMap<String,String>();
map.put("name","Zues");
map.put("sex","男");
map.put("idCard","200010");
map.put("year1","2000");
map.put("month1","07");
map.put("year2","2008");
map.put("month2","07");
map.put("gap","2");
map.put("zhuanye","计算机科学与技术");
map.put("type","研究生");
map.put("bianhao","2011020301");
map.put("nowy","2011");
map.put("nowm","01");
map.put("nowd","20220301");
//注意biyezheng_moban.doc文档位置,此例中为应用根目录
HWPFDocumentdocument=newExportDocTest().replaceDoc("biyezheng_moban.doc",map);
ByteArrayOutputStreamostream=newByteArrayOutputStream();
try{
document.write(ostream);
//输出word文件
OutputStreamouts=newFileOutputStream(destFile);
outs.write(ostream.toByteArray());
outs.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
/**
*
*@paramdestFile
*@paramfileCon
*/
publicvoidexportDoc(StringdestFile,StringfileCon){
try{
//doccontent
ByteArrayInputStreambais=newByteArrayInputStream(fileCon.getBytes());
POIFSFileSystemfs=newPOIFSFileSystem();
DirectoryEntrydirectory=fs.getRoot();
directory.createDocument("WordDocument",bais);
FileOutputStreamostream=newFileOutputStream(destFile);
fs.writeFilesystem(ostream);
bais.close();
ostream.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
/**
*读取word模板并替换变量
*@paramsrcPath
*@parammap
*@return
*/
publicHWPFDocumentreplaceDoc(StringsrcPath,Map<String,String>map){
try{
//读取word模板
FileInputStreamfis=newFileInputStream(newFile(srcPath));
HWPFDocumentdoc=newHWPFDocument(fis);
//读取word文本内容
RangebodyRange=doc.getRange();
//替换文本内容
for(Map.Entry<String,String>entry:map.entrySet()){
bodyRange.replaceText("${"+entry.getKey()+"}",entry
.getValue());
}
returndoc;
}catch(Exceptione){
e.printStackTrace();
returnnull;
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助。