java利用poi实现word、excel、pdf文件转html在线预览,文件下载

word、excel、pdf文件在线预览、文件下载

导入apache poi 相关jar包
在pom.xml 中引入依赖

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.11</version>
</dependency>

<dependency>
	<groupId>fr.opensagres.xdocreport</groupId>
	<artifactId>org.apache.poi.xwpf.converter.core</artifactId>
	<version>1.0.6</version>
</dependency>

<dependency>
	<groupId>fr.opensagres.xdocreport</groupId>
	<artifactId>org.apache.poi.xwpf.converter.xhtml</artifactId>
	<version>1.0.6</version>
</dependency>

百度云盘 poi.xwpf.converter相关jar包
链接:https://pan.baidu.com/s/1bZe71LstldJEiXdZ3X9Q_w
提取码:5g98

文件操作工具类如下:

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.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;

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.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.List;

/**
 * 文件操作工具
 */

public class FileHandleUtils {
	/**
	 * docx文件转换成html
	 * 
	 * @param tempPath
	 *            文件存放路径
	 * @param fileName
	 *             path+fileName
	 * @param outPutFile
	 *            预览html path+fileName
	 */
	public static void docxToHtml(String tempPath, String fileName, String outPutFile)
			throws TransformerException, IOException, ParserConfigurationException {

		XWPFDocument document = new XWPFDocument(new FileInputStream(fileName));
		XHTMLOptions options = XHTMLOptions.create().indent(4);
		File imageFolder = new File(tempPath);
		options.setExtractor(new FileImageExtractor(imageFolder));
		options.URIResolver(new FileURIResolver(imageFolder));
		File outFile = new File(outPutFile);
		outFile.getParentFile().mkdirs();
		OutputStream out = new FileOutputStream(outFile);
		XHTMLConverter.getInstance().convert(document, out, options);

	}

	/**
	 * doc文件转换成html
	 */
	public static void docToHtml(String tempPath, String fileName, String outPutFile)
			throws TransformerException, IOException, ParserConfigurationException {

		HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(fileName));
		WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
				DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
		wordToHtmlConverter.setPicturesManager(new PicturesManager() {
			public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches,
					float heightInches) {
				return "img/" + suggestedName;
			}
		});
		wordToHtmlConverter.processDocument(wordDocument);
		List<Picture> pics = wordDocument.getPicturesTable().getAllPictures();
		if (pics != null) {
			for (int i = 0; i < pics.size(); i++) {
				Picture pic = (Picture) pics.get(i);
				try {
					pic.writeImageContent(new FileOutputStream(tempPath + pic.suggestFullFileName()));
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}
		}
		Document htmlDocument = wordToHtmlConverter.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();
		writeFile(new String(out.toByteArray()), outPutFile);
	}

	/**
	 * excel .xls文件转换成html
	 */
	public static void HSSFToHtml(String tempPath, String fileName, String outPutFile)
			throws TransformerException, IOException, ParserConfigurationException {

		InputStream input = new FileInputStream(fileName);
		HSSFWorkbook excelBook = new HSSFWorkbook(input);
		ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter(
				DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
		excelToHtmlConverter.processWorkbook(excelBook);
		List pics = excelBook.getAllPictures();
		if (pics != null) {
			for (int i = 0; i < pics.size(); i++) {
				Picture pic = (Picture) pics.get(i);
				try {
					pic.writeImageContent(new FileOutputStream(tempPath + pic.suggestFullFileName()));
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}
		}
		Document htmlDocument = excelToHtmlConverter.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, "utf-8");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		serializer.setOutputProperty(OutputKeys.METHOD, "html");
		serializer.transform(domSource, streamResult);
		outStream.close();
		writeFile(new String(outStream.toByteArray()), outPutFile);
	}

	/**
	 * 将文件内容写入指定html文件
	 * @param content 内容
	 * @param outFilePath 输出文件路径 path+fileName
	 */
	private static void writeFile(String content, String outFilePath) {
		FileOutputStream fos = null;
		BufferedWriter bw = null;
		try {
			File file = new File(outFilePath);
			fos = new FileOutputStream(file);
			bw = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"));
			bw.write(content);
		} catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			try {
				if (bw != null)
					bw.close();
				if (fos != null)
					fos.close();
			} catch (IOException ie) {
			}
		}
	}

	/*文件下载*/
	public static boolean downloadFile(String filePath, String fileName, String downloadName,String contentType, HttpServletResponse response){
		boolean flag=true;
		try {
			File file = new File(filePath + fileName);
			if (!file.exists()) {
				flag = false;
			} else {
				FileInputStream fileInputStream = new FileInputStream(file);
				response.setHeader("Content-Disposition",
						"attachment;Filename=" + URLEncoder.encode(downloadName, "UTF-8"));
				response.setHeader("Content-Type", contentType);//设置格式类型
				OutputStream outputStream = response.getOutputStream();
				byte[] bytes = new byte[2048];
				int len = 0;
				while ((len = fileInputStream.read(bytes)) > 0) {
					outputStream.write(bytes, 0, len);
				}
				fileInputStream.close();
				outputStream.close();
			}
		}catch (IOException e){
			e.printStackTrace();
			flag = false;
		}
		return flag;
	}
}

controller中如下:

	/**
	 * 文件在线预览 
	 */
	@RequestMapping(value = "view", method = RequestMethod.GET)
	public void view(String fileId, HttpServletResponse response) {
		
		try {
			//根据文件Id查找文件信息
			FileUpload fileUpload = fileService.findFile(fileId);
			if(fileUpload==null){
				response.setContentType("text/html;charset=utf-8");
				PrintWriter out = response.getWriter();
				String message = "<div style='width:100%;text-align:center;color:red;'>文件不存在</div>";
				out.write(message);
				out.close();
				return;
			}
			String fileExtension = fileUpload.getFileEntity().getFileExtension();
			String path = fileUpload.getFileEntity().getFilePath();
			String fileName = path + fileUpload.getFileEntity().getFileId() + fileExtension;
			String outPutFile = path + "sample.html";
			//判断文件类型
			if (".doc".equals(fileExtension)) {
				FileHandleUtils.docToHtml(path, fileName, outPutFile);
			} else if (".docx".equals(fileExtension)) {
				FileHandleUtils.docxToHtml(path, fileName, outPutFile);
			} else if (".xls".equals(fileExtension)) {
				FileHandleUtils.HSSFToHtml(path, fileName, outPutFile);
			} else if (".pdf".equals(fileExtension)) {
				FileCopyUtils.copy(new FileInputStream(fileName), response.getOutputStream());
			} else {
				response.setContentType("text/html;charset=utf-8");
				PrintWriter out = response.getWriter();
				String message = "<div style='width:100%;text-align:center;color:red;'>抱歉!当前文件格式不支持预览</div>";
				out.write(message);
				out.close();
				return;
			}
			//将生成的html文件返回给前端页面
			FileCopyUtils.copy(new FileInputStream(outPutFile), response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值