/***
* 實現(xiàn)Word模板讀取替換內(nèi)容輸出
* @param filePath 模板路徑
* @param haderMap 頁眉數(shù)據(jù)
* @param bodyMap 內(nèi)容數(shù)據(jù)
* @param footMap 頁腳數(shù)據(jù)
*/
public
static
void
readwriteWord(String filePath, Map<String,String> haderMap,Map<String ,String> bodyMap,Map<String,String> footMap){
//讀取word模板
FileInputStream in =
null
;
try
{
in =
new
FileInputStream(
new
File(filePath));
}
catch
(FileNotFoundException e1) {
e1.printStackTrace();
}
HWPFDocument hdt =
null
;
try
{
hdt =
new
HWPFDocument(in);
}
catch
(IOException e1) {
e1.printStackTrace();
}
//讀取word頁眉內(nèi)容
Range harderRange= hdt.getHeaderStoryRange();
//替換word頁眉內(nèi)容
for
(Map.Entry<String, String> entry:haderMap.entrySet()){
harderRange.replaceText(
"${"
+ entry.getKey() +
"}"
, entry.getValue());
}
//讀取頁腳內(nèi)容
Range footRange=hdt.getFootnoteRange();
//替換頁腳內(nèi)容
for
(Map.Entry<String,String> entry:footMap.entrySet()){
footRange.replaceText(
"${"
+ entry.getKey().trim() +
"}"
, entry.getValue());
}
//讀取word文本內(nèi)容
Range bodyRange = hdt.getRange();
//替換文本內(nèi)容
for
(Map.Entry<String,String> entry: bodyMap.entrySet()) {
bodyRange.replaceText(
"${"
+ entry.getKey() +
"}"
,entry.getValue());
}
// PicturesTable picturesTable= hdt.getPicturesTable();
// //hdt.addPicture(bytes, XWPFDocument.PICTURE_TYPE_JPEG);
//
// FileInputStream fis = new FileInputStream("F:\\picture\\http_imgload.jpg");
// //將圖片添加到xlsx文件
// int picinx = hdt.addPicture(fis, XWPFDocument.PICTURE_TYPE_JPEG);
// fis.close();
//
ByteArrayOutputStream ostream =
new
ByteArrayOutputStream();
String fileName =
""
+System.currentTimeMillis();
fileName +=
".doc"
;
FileOutputStream out =
null
;
try
{
out =
new
FileOutputStream(
"E:\\test\\"
+fileName,
true
);
}
catch
(FileNotFoundException e) {
e.printStackTrace();
}
try
{
hdt.write(ostream);
}
catch
(IOException e) {
e.printStackTrace();
}
//輸出字節(jié)流
try
{
out.write(ostream.toByteArray());
}
catch
(IOException e) {
e.printStackTrace();
}
try
{
out.close();
}
catch
(IOException e) {
e.printStackTrace();
}
try
{
ostream.close();
}
catch
(IOException e) {
e.printStackTrace();
}
}