Java 实现word文档生成
(1)简单的word文档的生成,没有for循环输出数据。
创建
PoiUtil
类
package wordTest;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.model.io.HWPFOutputStream;
import org.apache.poi.hwpf.usermodel.Range;
public class PoiUtil {
public static void main(String[] args) {
String path = "G:\\wordTest.doc";
Map<String, String> map = new HashMap<String, String>();
map.put("begDate", "2015-02-03");
map.put("endDate", "2015-02-03");
map.put("deptName", "
日报
");
map.put("reportName", "Froan");
map.put("reportDate", "2015-02-03");
map.put("content", "Hello world! I am a gril.......");
String newPath = "G:\\
生成的测试
Word.doc";
replaceDoc(path,newPath, map);
// cp(path,newPath);
}
/**
*
读取
word
模板并替换变量
* @param
*
文件模板路径
* @throws IOException
*/
public static boolean replaceDoc(String srcPath,String newPath,Map<String,String> map)
{
//
读取
word
模板
try {
FileInputStream fis = new FileInputStream(new File(srcPath));
HWPFDocument doc = new HWPFDocument(fis);
// XSSFWorkbook doc=new XSSFWorkbook ();
//
读取
word
文本内容
Range bodyRange = doc.getRange();
for(Map.Entry<String,String> entry : map.entrySet()){
bodyRange.replaceText("${"+entry.getKey()+"}", entry.getValue());
}
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
doc.write(ostream);
OutputStream outs = new FileOutputStream(newPath);
outs.write(ostream.toByteArray());
outs.close();
return true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
/**
*
拷贝文件
*/
public static final boolean cp(String oldName,String newName){
try {
File file = new File(oldName);
if(!file.exists()||!file.isFile()){
return false;
}
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(newName);
byte[] buff = new byte[8912];
int byteRead = 0;
while((byteRead=fis.read(buff,0,8912))>0){
fos.write(buff,0,byteRead);
}
fis.close();
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("File copy error:"+e);
return false;
}
return true;
}
public static boolean writeDoc(String path,String text){
boolean res = false;
try {
byte b[]= text.getBytes();
FileOutputStream fs = new FileOutputStream(path);
HWPFOutputStream hos = new HWPFOutputStream();
hos.write(b,0,b.length);
hos.writeTo(fs);
hos.close();
res = true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
res = false;
}
return res;
}
}
|
所需
jar
包
另外需要创建
word
导出模板,如下
备注:该功能实现的只是在本地生成word文档,如果放在服务器上运行只是将word生成到了服务器指定位置,不会下载到客户端。