您的位置:首页 > 其它

POI 附件在线预览

2017-08-31 11:47 274 查看
package com.pde.xzjg.p9.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.FileUtils;
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.springframework.web.multipart.commons.CommonsMultipartFile;
import org.w3c.dom.Document;

import com.pde.ams.p9.service.LogWriter;
import com.pde.app.common.domain.PdeSessionBean;
import com.pde.app.common.params.PdpSystemParams;
import com.pde.xzjg.p9.domain.CauseJGbean;
import com.pde.xzjg.p9.domain.OrgInfo;
import com.pde.xzjg.p9.service.JGOneService;

import sun.misc.BASE64Encoder;

public class CommonTools {

/**
* @param uploadpath 需要转换的文件的路径
* @param parmas     获取工作空间的service
* @param session
* @param request
* @return   返回转换后的html路径
*/
public static void showView(String uploadpath,PdpSystemParams parmas,PdeSessionBean session,HttpServletRequest request,HttpServletResponse response){
String newPath = null;
if(uploadpath!=null && uploadpath.length()>0){
String compltePath = parmas.getValue(PdpSystemParams.AMS_WORKSPACE)+uploadpath;//得到要转换的文件的全路径
int index = compltePath.lastIndexOf("/")+1;//获取到最后一个/的位置索引
try{
if(compltePath.substring(index).endsWith(".DOC")||compltePath.substring(index).endsWith(".doc")){
newPath = CommonTools.wordtoHtml(uploadpath, parmas, session, request);
if(newPath!=null && newPath.length()>0){
newPath = newPath.replaceAll("/", "\\\\\\\\");
}
}else if(compltePath.substring(index).endsWith(".XLS")||compltePath.substring(index).endsWith(".xls")){
newPath = CommonTools.exceltoHtml(uploadpath, parmas, session, request);
if(newPath!=null && newPath.length()>0){
newPath = newPath.replaceAll("/", "\\\\\\\\");
}

}else{

}
File readFile = null;
try {
readFile = new File(newPath);
FileInputStream hFile = new FileInputStream(readFile); // 以byte流的方式打开文件 d:\1.gif
int i=hFile.available(); //得到文件大小
byte data[]=new byte[i];
hFile.read(data); //读数据
hFile.close();
//response.setContentType("application/msword"); //设置返回的文件类型
response.setContentType("text/html;charset=utf-8");
OutputStream toClient=response.getOutputStream(); //得到向客户端输出二进制数据的对象
toClient.write(data); //输出数据
toClient.close();
//readFile.delete();//删除转换后的临时文件
} catch (Exception e) {
PrintWriter toClient;
try {
toClient = response.getWriter();
//到向客户端输出文本的对象
response.setContentType("text/html;charset=UTF-8");
toClient.write("无法打开图片!");
toClient.close();
//readFile.delete();//删除转换后的临时文件
} catch (IOException e1) {
e1.printStackTrace();
}
}
}catch(Exception e){
e.printStackTrace();
}

}
}

public static String wordtoHtml(String uploadpath,PdpSystemParams parmas,PdeSessionBean session,HttpServletRequest request) throws Exception {
UUID uuid = UUID.randomUUID();//生成一个uuid,为新文件的名字(防止与别的转换后的文件有名字冲突)
String compltePath = parmas.getValue(PdpSystemParams.AMS_WORKSPACE)+uploadpath;//得到要转换的文件的全路径
int index = compltePath.lastIndexOf("/")+1;//获取到最后一个/的位置索引
String newPath = compltePath.substring(0,index)+session.getUserId()+"/";
//创建新的文件夹,以用户id为文件名
//request.getSession().getServletContext().setAttribute("tempFilePath", newPath);
File dir = new File(newPath);
if(!dir.isDirectory()){
if(!dir.exists()){
dir.mkdirs();
}
}
String oldPath = compltePath.substring(0,index);
String fileName = compltePath.substring(index);
String randomNumber = uuid.toString();
String oldAllpath = oldPath + fileName;
oldAllpath = oldAllpath.replaceAll("/", "\\\\\\\\");
File f = new File(oldAllpath);
InputStream input = new FileInputStream(f);
String content = null;

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 widthInches, float heightInches) {
return suggestedName;
}
});
wordToHtmlConverter.processDocument(wordDocument);

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, "utf-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.METHOD, "html");
serializer.transform(domSource, streamResult);
outStream.close();
content = new String(outStream.toByteArray(),"utf-8");

List pics = wordDocument.getPicturesTable().getAllPictures();
if (pics != null) {
for (int i = 0; i < pics.size(); i++) {
Picture pic = (Picture) pics.get(i);
try {
ByteArrayOutputStream outStreamImg = new ByteArrayOutputStream();
pic.writeImageContent(outStreamImg);
String imgStr = new BASE64Encoder().encodeBuffer(outStreamImg.toByteArray());//base64加密
content = content.replaceAll("img src=\""+pic.suggestFullFileName()+"\"",
"img src=\"data:image/png;base64,"+imgStr+ "\"");
outStreamImg.close();
/*pic.writeImageContent(new FileOutputStream(oldPath
+ pic.suggestFullFileName()));*/

} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
FileUtils.writeStringToFile(
new File(newPath + randomNumber + ".html"), content, "utf-8");
return newPath + randomNumber + ".html";
}

/**
* @param uploadpath
* @param parmas
* @param session
* @param request
* @return
* @throws Exception
*/
public static String exceltoHtml(String uploadpath,PdpSystemParams parmas,PdeSessionBean session,HttpServletRequest request) throws Exception {
UUID uuid = UUID.randomUUID();//生成一个uuid,为新文件的名字(防止与别的转换后的文件有名字冲突)
String compltePath = parmas.getValue(PdpSystemParams.AMS_WORKSPACE)+uploadpath;//得到要转换的文件的全路径
int index = compltePath.lastIndexOf("/")+1;//获取到最后一个/的位置索引
String newPath = compltePath.substring(0,index)+session.getUserId()+"/";
//创建新的文件夹,以用户id为文件名
//request.getSession().getServletContext().setAttribute("tempFilePath", newPath);

File dir = new File(newPath);
if(!dir.isDirectory()){
if(!dir.exists()){
dir.mkdirs();
}
}
String oldPath = compltePath.substring(0,index);
String fileName = compltePath.substring(index);
String randomNumber = uuid.toString();
String oldAllpath = oldPath + fileName;
oldAllpath = oldAllpath.replaceAll("/", "\\\\\\\\");
File f = new File(oldAllpath);
InputStream input = new FileInputStream(f);

HSSFWorkbook excelBook = new HSSFWorkbook(input);
excelBook.setSheetName(0, "  ");//不在页面显示sheet的名字
ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter(
DocumentBuilderFactory.newInstance().newDocumentBuilder()
.newDocument());
excelToHtmlConverter.setOutputColumnHeaders(false);//把excel转换成html 去掉序号列
excelToHtmlConverter.setOutputRowNumbers(false);//把excel转换成html 去掉序号列
excelToHtmlConverter.processWorkbook(excelBook);

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();

String content = new String(outStream.toByteArray(),"utf-8");
List pics = excelBook.getAllPictures();
if (pics != null) {
for (int i = 0; i < pics.size(); i++) {
Picture pic = (Picture) pics.get(i);
try {
ByteArrayOutputStream outStreamImg = new ByteArrayOutputStream();
pic.writeImageContent(outStreamImg);
String imgStr = new BASE64Encoder().encodeBuffer(outStreamImg.toByteArray());
content = content.replaceAll("img src=\""+pic.suggestFullFileName()+"\"",
"img src=\"data:image/png;base64,"+imgStr+ "\"");
outStreamImg.close();
/*pic.writeImageContent(new FileOutputStream(oldPath
+ pic.suggestFullFileName()));*/

} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
FileUtils.writeStringToFile(
new File(newPath + randomNumber + ".html"), content, "utf-8");
return newPath + randomNumber + ".html";
}

/**
* @param request
* @param uploadpath 模块类型/当前年份/(如果涉及季度|月就加季度|月)/     如:jg1/2017
* @param parmas   获取工作空间
* @param jgoneService  获取机构编码
* @param session
* @return
*/
public static String upLoad(HttpServletRequest request,String uploadpath, CommonsMultipartFile file,PdpSystemParams parmas,JGOneService jgoneService,PdeSessionBean session){
//将当前上下文初始化给  CommonsMutipartResolver (多部分解析器)
String fileNameNew = null;
if(file!=null)
{
String fileDir = parmas.getValue(PdpSystemParams.AMS_WORKSPACE)+"/xzjg/"+ uploadpath + "/";
File dir = new File(fileDir);
if(!dir.isDirectory()){
if(!dir.exists()){
dir.mkdirs();
}
}
String suffexName = (file.getOriginalFilename()).substring( (file.getOriginalFilename()).lastIndexOf(".")+1 );
String newFileName = UUID.randomUUID().toString() + "." + suffexName;
//文件格式:机构编码+userid+uuid文件名(用uuid替代原始文件名,原始文件名(file.getOriginalFilename())有中文时,传到前台时会有乱码,导致异常)
OrgInfo info = jgoneService.getOrgInfoByUserId(String.valueOf(session.getUserId()));
String path=parmas.getValue(PdpSystemParams.AMS_WORKSPACE)+"/xzjg/" + uploadpath +"/"+info.getDic_value()+"_"+session.getUserId()+"_"+newFileName;
//上传
try {
file.transferTo(new File(path));
fileNameNew = newFileName;
return fileNameNew;
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
LogWriter.saveErr("XZJG", e.getMessage());
}

}

return fileNameNew;
}

public static void delAllFile(String folderPath) {
File file = new File(folderPath);
if (file.exists()) {
file.delete();
}
}

/**
* 获取已经存在的年度
* @param bean 查询的类型获取来源 例如 jg1 jg2 jg3 jg4 jg5
* @param jgoneService
* @return
*/
public static List<String> getYear(CauseJGbean bean,JGOneService jgoneService){
List<String> year = jgoneService.getYear(bean);
return year;
}

/**
* 获取所有的管理单位
* @return
*/
public static List<String> getUnit(JGOneService jgoneService){
List<String> unit = jgoneService.getUnit();
return unit;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  POI