WORD替换指定内容、WORD转成HTML主要片段代码
1、WORD按${key}格式指定替换内容
/**
* 格式:${key}
*/
public static boolean replaceAndGenerateWord(String srcPath, String destPath, Map<String, Object> map) throws Exception{
String[] sp = srcPath.split("\\.");
String[] dp = destPath.split("\\.");
if ((sp.length > 0) && (dp.length > 0)) {
// WORD2007
if (sp[sp.length - 1].equalsIgnoreCase("docx")) {
XWPFDocument document = new XWPFDocument( POIXMLDocument.openPackage(srcPath));
Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
while (itPara.hasNext()) {
XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
List<XWPFRun> runs = paragraph.getRuns();
for (int i = 0; i < runs.size(); i++) {
String oneparaString = runs.get(i).toString();
if(oneparaString.contains("${")&&oneparaString.contains("}")){//${key}
//oneparaString = oneparaString.replace("${", "").replace("}", "");
for (Map.Entry<String, Object> entry : map.entrySet()) {
if(oneparaString.contains("${"+entry.getKey()+"}")){
oneparaString = oneparaString.replace( "${"+entry.getKey()+"}", entry.getValue()==null?"":entry.getValue().toString());
}
}
runs.get(i).setText(oneparaString, 0);
}else if(oneparaString.contains("${")&&!oneparaString.contains("}")){//${
String comparekey = "";
int pos = 0;
comparekey+=oneparaString.substring(oneparaString.indexOf("${"), oneparaString.length()).replace("${", "");
for (int j = i+1; j < runs.size(); j++) {
if(runs.get(j).toString().contains("}")){
String str = runs.get(j).toString();
comparekey+=str.substring(0, str.indexOf("}"));
pos = j;
break;
}else{
comparekey+=runs.get(j).toString();
}
}
for (Map.Entry<String, Object> entry : map.entrySet()) {
if(comparekey.equals(entry.getKey())){
comparekey = comparekey.replace( entry.getKey(), entry.getValue()==null?"":entry.getValue().toString());
}
}
for(int k=i;k<=pos;k++){
if(k==i){
runs.get(k).setText(comparekey, 0);
}else{
runs.get(k).setText("", 0);
}
}
}else if(oneparaString.contains("$")&&!oneparaString.contains("${")){//$
String comparekey = "";
int pos = 0;
for (int j = i+1; j < runs.size(); j++) {
String str = runs.get(j).toString();
if(str.contains("{")&&str.contains("}")){
comparekey+=str.substring(str.indexOf("{"), str.indexOf("}")).replace("{", "");
pos = j;
break;
}else if(str.contains("{")&&!str.contains("}")){
comparekey+=str.substring(str.indexOf("{"),str.length()).replace("{", "");
}else if(!str.contains("{")&&str.contains("}")){
comparekey+=str.substring(0,str.indexOf("}"));
pos = j;
break;
}else{
comparekey+=str;
}
}
for (Map.Entry<String, Object> entry : map.entrySet()) {
if(comparekey.equals(entry.getKey())){
comparekey = comparekey.replace( entry.getKey(), entry.getValue()==null?"":entry.getValue().toString());
}
}
for(int k=i;k<=pos;k++){
if(k==i){
runs.get(k).setText(comparekey, 0);
}else{
runs.get(k).setText("", 0);
}
}
}
}
}
// 表格
Iterator<XWPFTable> itTable = document.getTablesIterator();
while (itTable.hasNext()) {
XWPFTable table = (XWPFTable) itTable.next();
int rcount = table.getNumberOfRows();
for (int i = 0; i < rcount; i++) {
XWPFTableRow row = table.getRow(i);
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
String cellTextString = cell.getText();
for (Entry<String, Object> e : map.entrySet()) {
if (cellTextString.contains(e.getKey()))
cellTextString = cellTextString.replace(e.getKey(),e.getValue()==null?"":e.getValue().toString());
}
cell.removeParagraph(0);
cell.setText(cellTextString);
}
}
}
FileOutputStream outStream = null;
outStream = new FileOutputStream(destPath);
document.write(outStream);
outStream.close();
return true;
} else if ((sp[sp.length - 1].equalsIgnoreCase("doc")) && (dp[dp.length - 1].equalsIgnoreCase("doc"))) { //WORD2003
HWPFDocument document = null;
document = new HWPFDocument(new FileInputStream(srcPath));
Range range = document.getRange();
//执行替换目次损坏,未找到解决方法
for (Map.Entry<String, Object> entry : map.entrySet()) {
range.replaceText("${"+entry.getKey()+"}", entry.getValue()==null?"":entry.getValue().toString());
}
FileOutputStream outStream = null;
outStream = new FileOutputStream(destPath);
document.write(outStream);
outStream.close();
return true;
} else {
return false;
}
} else {
return false;
}
}
public class PoiWordToHtmlUtil {
public static void PoiWordToHtml(String fileSrcPath,String srcfileName,String fileDesPath,String desHtmlName) throws Exception{
String[] sp = srcfileName.split("\\.");
if (sp.length > 0) {// 判断文件有无扩展名
if (sp[sp.length - 1].equalsIgnoreCase("docx")) {
docxToHtml(fileSrcPath,srcfileName,fileDesPath,desHtmlName);
}else if ((sp[sp.length - 1].equalsIgnoreCase("doc"))){
docToHtml(fileSrcPath,srcfileName,fileDesPath,desHtmlName);
}
}
}
/**
* word2003转html
* @param fileSrcPath
* @param fileName
* @param fileDesPath
* @param desHtmlName
* @throws Exception
*/
public static void docToHtml(String fileSrcPath,String srcfileName,String fileDesPath,String desHtmlName) throws Exception{
InputStream input = new FileInputStream(fileSrcPath + srcfileName);
HWPFDocument wordDocument = new HWPFDocument(input);
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
wordToHtmlConverter.setPicturesManager(new PicturesManager() {
public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float arg3, float arg4) {
return suggestedName;
}
});
wordToHtmlConverter.processDocument(wordDocument);
List<Picture> pics = wordDocument.getPicturesTable().getAllPictures();
if (pics != null) {
for (int i = 0; i < pics.size(); i++) {
Picture pic = pics.get(i);
try {
pic.writeImageContent(new FileOutputStream(fileSrcPath + pic.suggestFullFileName()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Document htmlDocument = wordToHtmlConverter.getDocument();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource(htmlDocument);
StreamResult streamResult = new StreamResult(outStream);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "GBK");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.METHOD, "html");
serializer.transform(domSource, streamResult);
outStream.close();
String content = new String(outStream.toByteArray());
FileUtils.writeStringToFile(new File(fileDesPath, desHtmlName), content, "GBK");
}
/**
* word2007转html
* @param fileSrcPath
* @param fileName
* @param fileDesPath
* @param desHtmlName
* @throws Exception
*/
public static void docxToHtml(String fileSrcPath,String srcfileName,String fileDesPath,String desHtmlName) throws Exception{
InputStream in = new FileInputStream(fileSrcPath + srcfileName);
XWPFDocument document = new XWPFDocument(in);
File imageFolderFile = new File(fileSrcPath+"/img/");
XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(imageFolderFile));
options.setExtractor(new FileImageExtractor(imageFolderFile));
OutputStream out = new FileOutputStream(new File(fileDesPath+desHtmlName));
XHTMLConverter.getInstance().convert(document, out, options);
}
}
3、相关包
相关包:POI3.9涉及包下载