JAVA项目中,导出Word使用比较多的,都是封装好的,例如Easypoi。当然我们也可以使用比较原始的方式,在Word中添加书签,按照Word模板书签,导出我们需要的数据到Word书签中。
1,封装导出Word的工具类
import lombok.extern.slf4j.Slf4j;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* 使用书签(bookmark)导出word的工具类
*/
@Slf4j
public class PrintWord {
public synchronized static void modifyDocumentAndSave(Map<String, String> bookMarkMap,String filePath,String tmpDir,String fileName,HttpServletResponse response) throws IOException, SAXException, ParserConfigurationException,TransformerException {
// 使用java.util打开文件
File file = new File(filePath);
ZipFile docxFile = new ZipFile(file);
// 返回ZipEntry应用程序接口
ZipEntry documentXML = docxFile.getEntry("word/document.xml");
InputStream documentXMLIS = docxFile.getInputStream(documentXML);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document doc = dbf.newDocumentBuilder().parse(documentXMLIS);
// linkMan tel proCode companyName fundName fundCode sysProCode
/**
* 书签列表
*/
NodeList this_book_list = doc.getElementsByTagName("w:bookmarkStart");
if (this_book_list.getLength() != 0) {
for (int j = 0; j < this_book_list.getLength(); j++) {
// 获取每个书签
Element oldBookStart = (Element) this_book_list.item(j);
// 书签名
String bookMarkName = oldBookStart.getAttribute("w:name");
// 书签名,跟需要替换的书签传入的map集合比较
for (Map.Entry<String, String> entry : bookMarkMap.entrySet()) {
// 书签处值开始
Node wr = doc.createElement("w:r");
Node wt = doc.createElement("w:t");
Node wt_text = doc.createTextNode(entry.getValue());
wt.appendChild(wt_text);
wr.appendChild(wt);
// 书签处值结束
if (entry.getKey().equals(bookMarkName)) {
Element node = (Element) oldBookStart.getNextSibling();
// 获取兄弟节点w:r
// 如果书签处无文字,则在书签处添加需要替换的内容,如果书签处存在描述文字,则替换内容,用w:r
NodeList wtList = node.getElementsByTagName("w:t");
// 获取w:r标签下的显示书签处内容标签w:t
if (wtList.getLength() == 0) {
// 如果不存在,即,书签处本来就无内容,则添加需要替换的内容
oldBookStart.appendChild(wr);
} else {
// 如果书签处有内容,则直接替换内容
Element wtNode = (Element) wtList.item(0);
wtNode.setTextContent(entry.getValue());
}
}
}
}
}
//这个工具类可以将任何格式XML报文转化成你想要的XML格式
Transformer t = TransformerFactory.newInstance().newTransformer();
//字节数组流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
t.transform(new DOMSource(doc), new StreamResult(baos));
//目标文件夹是否存在,不存在创建
File tmpfile = new File(tmpDir);
if(!tmpfile.exists()){
tmpfile.mkdir();
}
ZipOutputStream docxOutFile = new ZipOutputStream(new FileOutputStream(tmpDir+fileName));
Enumeration entriesIter = docxFile.entries();
while (entriesIter.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entriesIter.nextElement();
// 如果是document.xml则修改,别的文件直接拷贝,不改变word的样式
if (entry.getName().equals("word/document.xml")) {
byte[] data = baos.toByteArray();
docxOutFile.putNextEntry(new ZipEntry(entry.getName()));
docxOutFile.write(data, 0, data.length);
docxOutFile.closeEntry();
} else {
InputStream incoming = docxFile.getInputStream(entry);
// 此处设定值需慎重,如果设置小了,会破坏word文档,至于为什么会破坏,自己去思考
byte[] data = new byte[1024 * 512];
int readCount = incoming.read(data, 0, (int) entry.getSize());
if(readCount != -1){
docxOutFile.putNextEntry(new ZipEntry(entry.getName()));
docxOutFile.write(data, 0, readCount);
docxOutFile.closeEntry();
}
}
}
//导出的文件写入完成,再将已经写好的文件响应到浏览器端
docxOutFile.close();
byte[] buffer = new byte[1024];
// 配置文件下载
response.setContentType("application/octet-stream");
// 下载文件能正常显示中文
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
FileInputStream inputStream = null;
BufferedInputStream bufferedInputStream = null;
// 实现文件下载
try {
inputStream = new FileInputStream(tmpDir+fileName);
bufferedInputStream = new BufferedInputStream(inputStream);
OutputStream outputStream = response.getOutputStream();
int i = bufferedInputStream.read(buffer);
while (i != -1) {
outputStream.write(buffer, 0, i);
i = bufferedInputStream.read(buffer);
}
outputStream.flush();
outputStream.close();
}catch (Exception e) {
log.error("Download failed!");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedInputStream != null) {
try {
bufferedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
delFileWord(tmpDir,fileName);//这一步看具体需求,要不要删
}
}
/**
* 删除零时生成的文件
*/
public static void delFileWord(String filePath, String fileName){
File file =new File(filePath+fileName);
File file1 =new File(filePath);
file.delete();
file1.delete();
}
}
2,直接调用导出方法
//由于前端多个请求进入该方法,所以导出的方法需要给多个线程加锁,使得导出Word方法同步,否则文件没有写入完成,就读取写入到浏览器端,可能为空文件夹
//params:是一个HashMap,key对应Word中的书签名,value用来替换书签的值。
//templatePath:导出Word模板文件路径
// templateName:导出Word模板文件文件名
//filePath:需要存放临时导出Word文件的路径
//fileName:fileName导出Word文件的文件名
PrintWord.modifyDocumentAndSave(params, templatePath + templateName, filePath, fileName, response);