Word根据模板生成数据
就是有个模板,完全保留模板样式的情况下,在相应的地方更改或保留数据
第一个类:
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
public class WordUtil {
//参数按顺序分别是模板路径,文件输出到的路径,替换的内容
public static void WriteWordByMB(String pathIn,String PathOut,Map<String, Object> changeMap){
try {
WordTemplate template = null;
//先获取模板
File filein = new File(pathIn);
FileInputStream fileInputStream = null;
fileInputStream = new FileInputStream(filein);
template = new WordTemplate(fileInputStream);
//替换模板内容
template.replaceTag(changeMap);
//导出
File fileout = new File(PathOut);
FileOutputStream out;
out = new FileOutputStream(fileout);
BufferedOutputStream bos = new BufferedOutputStream(out);
template.write(bos);
fileInputStream.close();
out.close();
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
里面调用的另一个类
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import com.lowagie.text.Document;
/**
* 仅支持对docx文件的文本及表格中的内容进行替换
* 模板仅支持 ${key} 标签
* @author JianQiu
*
*/
public class WordTemplate {
private static HWPFDocument document;
/**
* 初始化模板内容
* @param inputStream 模板的读取流(doc文件)
* @throws IOException
*/
public WordTemplate(InputStream inputStream) throws IOException{
document = new HWPFDocument(inputStream);
}
public void replaceTag(Map<String, Object> changeMap){
Range range=document.getRange();
for (Map.Entry<String,Object> entry: changeMap.entrySet()) {
range.replaceText("${" + entry.getKey() + "}",
String.valueOf(entry.getValue()));
}
}
public void write(OutputStream outputStream) throws IOException{
document.write(outputStream);
}
}
文件夹不一定存在的话
public static void WriteWordByMB(String pathIn, String pathOut, Map<String, Object> changeMap, String FileName) {
try {
// 先获取模板
FileInputStream fileInputStream = new FileInputStream(pathIn);
WordTemplate template = new WordTemplate(fileInputStream);
// 替换模板内容
template.replaceTag(changeMap);
File f = new File(pathOut);
// 判断文件夹是否已经存在,如果不存在重新建
if (!f.exists()) {
f.mkdirs();
}
// 导出
FileOutputStream out = new FileOutputStream(pathOut + "/" + FileName);
BufferedOutputStream bos = new BufferedOutputStream(out);
template.write(bos);
fileInputStream.close();
out.close();
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
以上方法只适用于doc
docx方法可以试试这个(我没试过的……):https://blog.csdn.net/sadwxds/article/details/51331060