前台传字符串导出word

package com.yunfengtech.common;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;

import org.apache.log4j.Logger;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.pdf.BaseFont;

public class HtmlToWord {

	private static Logger logger = Logger.getLogger("default");

	public static boolean writeWordFile(String inputFile, String outputFile)
			throws Exception {
		boolean w = false;
		outputFile = getUrl();
		logger.error("export word file dir is :" + outputFile);
		if (!"".equals(outputFile)) {
			// 检查目录是否存在
			File fileDir = new File(outputFile);
			logger.error("export word file dir is exist :" + fileDir.exists());
			if (fileDir.exists()) {
				// 生成临时文件名称
				String fileName = "report.doc";
				// IE兼容问题
				inputFile = inputFile.replaceAll("colSpan", "colspan")
						.replaceAll("rowSpan", "rowspan")
						.replaceAll("cellSpacing", "cellspacing")
						.replaceAll("\"", "\'");
				ITextRenderer renderer = new ITextRenderer();
				ITextFontResolver fontResolver = renderer.getFontResolver();
				try{
					if(isWindowsSystem()){
						fontResolver.addFont("C:/Windows/fonts/simsun.ttc",	BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
					}else{
						fontResolver.addFont("/usr/share/fonts/chinese/TrueType/simsun.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
					}
				}catch(Exception e1){
					e1.printStackTrace();
					logger.error("export word addFont exception :"+e1);
				}finally{
					
				}

				StringBuffer html = new StringBuffer();
				html.append("<!DOCTYPE html PUBLIC \'-//W3C//DTD XHTML 1.0 Transitional//EN\' \'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\'>");
				html.append("<html xmlns=\'http://www.w3.org/1999/xhtml\'>")
						.append("<head>")
						.append("<meta http-equiv=\'Content-Type\' content=\'text/html; charset=UTF-8\' />")
						.append("<style type=\'text/css\' mce_bogus=\'1\'>body {font-family: SimSun;} .reportTitle{font-size:20pt;font-weight:bold;}</style>")
						.append("</head>").append("<body>")
						.append(inputFile);
				html.append("</body></html>");

				String content = html.toString();
				ByteArrayInputStream bais = null;
				POIFSFileSystem poifs = null;
				FileOutputStream ostream = null;
				try{
					byte b[] = content.getBytes();
					bais = new ByteArrayInputStream(b);
					poifs = new POIFSFileSystem();
					DirectoryEntry directory = poifs.getRoot();
					@SuppressWarnings("unused")
					DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
					ostream = new FileOutputStream(outputFile + fileName);
					poifs.writeFilesystem(ostream);
				}catch(Exception e){
					e.printStackTrace();
					logger.error("export word exception :"+e);
				}finally{
					if(bais != null){
						bais.close();
					}
					if(ostream != null){
						ostream.close();
					}
				}
			}
		}
		
		return w;
	}
	
	public static String getUrl() {
		String path = HtmlToWord.class.getProtectionDomain().getCodeSource()
				.getLocation().getPath();
		int index = path.lastIndexOf("WEB-INF/lib");
		if (index == -1) {
			index = path.lastIndexOf("WEB-INF/classes");
		}

		String realPath = path.substring(0, index);
		realPath = realPath.replace("%20", " ");
		return realPath;
	}
	
	public static Boolean isWindowsSystem(){
		Boolean b = false ;
		String os = System.getProperties().getProperty("os.name");
		logger.error("the os is :"+os);
		if(os != null && os.toLowerCase().startsWith("windows")){
			b = true;
		}
		return b;
	}

}

猜你喜欢

转载自ohmyg.iteye.com/blog/2252945