場景介紹
因公司項目中需要使用到文件交互,因此在網上找了一個demo做了點修改,原項目功能只有上傳和下載,現要求在線預覽pdf word excel 文件,所以在原來的基礎上進行修改使其支持在線預覽,圖片和pdf 的在線預覽比較簡單,word excel 的預覽實現方式是先將word 和excel 文件 轉換成具有一定格式的html 然後輸出在界面上,目前只支持.xls 和 .doc 文件預覽
準備工作
1.需要用到的 jar 用於word excel的解析
2. PoiUtil2 類 用於解析word excel 的工具類
package fileServer.util;
import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
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.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class PoiUtil2 {
public static final String dtLong = "yyyyMMddHHmmss";
static DateFormat df = new SimpleDateFormat(dtLong);
/**
* Excel 轉爲 HTML
* @param fileName
* @param outputFile
* @throws FileNotFoundException
* @throws IOException
* @throws ParserConfigurationException
* @throws TransformerConfigurationException
* @throws TransformerException
*/
public static void excelToHtml(String fileName, String outputFile)
throws FileNotFoundException, IOException, ParserConfigurationException,
TransformerConfigurationException, TransformerException {
String htmlStr = excelPareToHtmlString(fileName);
writeFile(htmlStr, outputFile);
}
public static String excelPareToHtmlString(String fileName) throws FileNotFoundException, IOException, ParserConfigurationException,
TransformerConfigurationException, TransformerException {
InputStream is = new FileInputStream(fileName);
HSSFWorkbook excelBook = new HSSFWorkbook(is);
ExcelToHtmlConverter ethc = new ExcelToHtmlConverter(
DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
ethc.setOutputColumnHeaders(false);
ethc.setOutputRowNumbers(false);
ethc.processWorkbook(excelBook);
Document htmlDocument = ethc.getDocument();
ByteArrayOutputStream out = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource(htmlDocument);
StreamResult streamResult = new StreamResult(out);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.METHOD, "html");
serializer.transform(domSource, streamResult);
out.close();
String htmlStr = new String(out.toByteArray(),"UTF-8");
htmlStr = htmlStr.replace("<h2>Sheet1</h2>", "")
.replace("<h2>Sheet2</h2>", "")
.replace("<h2>Sheet3</h2>", "")
.replace("<h2>Sheet4</h2>", "")
.replace("<h2>Sheet5</h2>", "");
return htmlStr;
}
/**
* Word 轉爲 HTML
*
* @param fileName
* @param outputFile
* @throws IOException
* @throws ParserConfigurationException
* @throws TransformerException
*/
// public static void wordToHtml(String fileName, String outputFile) throws
// IOException, ParserConfigurationException, TransformerException {
// String htmlStr = wordParseToHtmlString(fileName,null,null);
// writeFile(htmlStr, outputFile);
// }
public static String wordParseToHtmlString(String fileName, String imageStoragePath,HttpServletRequest request)throws
IOException, ParserConfigurationException, TransformerException {
HWPFDocument wordDoc = new HWPFDocument(new FileInputStream(fileName));
WordToHtmlConverter wthc = new WordToHtmlConverter(
DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
//這裏用來處理word 中的圖片 保存到服務器本地磁盤並且 返回在線可訪問的地址
wthc.setPicturesManager(new PicturesManager() {
@Override
public String savePicture(byte[] bytes, PictureType pt, String string, float f, float f1) {
//文件命名與FileUpLload上傳文件名稱規則一致
String extension = pt.getExtension();
//因爲服務會給上傳的文件追加時間搓防止文件重複 oldName 上傳之前的文件名稱
String oldName = System.currentTimeMillis() + "." + extension;
String name = df.format(new Date()) + "-" + oldName;
try {
String targetPath = imageStoragePath + name;
FileOutputStream out = new FileOutputStream(targetPath);
out.write(bytes);
out.close();
String webroot = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
String fileurl = webroot + "/download?name=" + name;
name = fileurl;
//返回在線可訪問的地址 如 http://localhost:8000/download?name=1.jpg;
} catch (Exception e) {
e.printStackTrace();
}
return name;
}
});
wthc.processDocument(wordDoc);
List<Picture> pics = wordDoc.getPicturesTable().getAllPictures();
if (null != pics && pics.size() > 0) {
for (Picture pic : pics) {
String suggestFullFileName = pic.suggestFullFileName();
pic.writeImageContent(new FileOutputStream(suggestFullFileName));
}
}
Document htmlDocument = wthc.getDocument();
ByteArrayOutputStream out = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource(htmlDocument);
StreamResult streamResult = new StreamResult(out);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.METHOD, "html");
serializer.transform(domSource, streamResult);
out.close();
String htmlStr = new String(out.toByteArray(),"UTF-8");
return htmlStr;
}
public static void writeFile(String content, String path) {
FileOutputStream fos = null;
BufferedWriter bw = null;
File file = new File(path);
try {
fos = new FileOutputStream(file);
bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
bw.write(content);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (null != bw) {
bw.close();
}
if (null != fos) {
fos.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
PoiUtil2.excelToHtml("C:\\Users\\-AiYuan\\Desktop\\20190508001.xls", "C:\\Users\\-AiYuan\\Desktop\\test.html");
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
// try {
// PoiUtil2.wordToHtml("C:\\Users\\-AiYuan\\Desktop\\安卓掃描槍對接文檔 .doc","C:\\Users\\-AiYuan\\Desktop\\test2.html");
// } catch (IOException ex) {
// logger.error(ex);
// } catch (ParserConfigurationException ex) {
// logger.error(ex);
// } catch (TransformerException ex) {
// logger.error(ex);
// }
}
}
預覽圖片,pdf
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 省略通請求地址 //localhost:8000/download?name=1.jpg; 獲取文件代碼
//假裝這個file 是通過地址
File file = new File("C:\\Users\\-AiYuan\\Desktop\\1.jpg");
previewFile(response, file, oldName);
}
//預覽文件 圖片和dpf 都可以用此方法預覽
void previewFile(HttpServletResponse response, File file, String oldName) {
//指定瀏覽器內部打開
response.setHeader("Content-Disposition", "inline; filename=\"" + oldName + "\"");
writeFile(response, file);
}
// 寫入文件
void writeFile(HttpServletResponse response, File file) {
ServletOutputStream os = null;
FileInputStream is = null;
BufferedOutputStream bos = null;
try {
os = response.getOutputStream();
is = new FileInputStream(file);
bos = new BufferedOutputStream(os);
byte[] len = new byte[1024];
int read = 0;
while ((read = is.read(len)) != -1) {
bos.write(len, 0, read);
}
bos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
預覽word
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 省略通請求地址 //localhost:8000/download?name=1.jpg; 獲取文件代碼
//假裝這個file 是通過地址
File file = new File("C:\\Users\\-AiYuan\\Desktop\\1.jpg");
//imageStoragePath word 中圖片要存儲的路徑
previewOfficeDoc(request, response, file.getAbsolutePath(), imageStoragePath);
}
//預覽word .doc 文件
void previewOfficeDoc(HttpServletRequest request, HttpServletResponse response,String fileAbsolutePath, String buildPath) {
ServletOutputStream os = null;
try {
os = response.getOutputStream();
//調用工具類的 word 轉html
String wordParseToHtmlString = PoiUtil2.wordParseToHtmlString(fileAbsolutePath, buildPath, request);
os.write(wordParseToHtmlString.getBytes("UTF-8"));
os.flush();
} catch (IOException | ParserConfigurationException | TransformerException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
預覽excel
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 省略通請求地址 //localhost:8000/download?name=1.jpg; 獲取文件代碼
//假裝這個file 是通過地址
File file = new File("C:\\Users\\-AiYuan\\Desktop\\1.jpg");
previewOfficeXls(response, file.getAbsolutePath());
}
//預覽excel .xls 文件
void previewOfficeXls(HttpServletResponse response, String fileAbsolutePath) {
ServletOutputStream os = null;
try {
os = response.getOutputStream();
//調用 解析工具解析excel
String wordParseToHtmlString = PoiUtil2.excelPareToHtmlString(fileAbsolutePath);
os.write(wordParseToHtmlString.getBytes("UTF-8"));
os.flush();
} catch (IOException | ParserConfigurationException | TransformerException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}