word转html(一)

原创
2016/02/03 17:28
阅读数 3.5K

一、依赖的包,部署环境

二、后台代码实现

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

/**
	 *
	 * <p>【导入word文件,解析word文件转换成HTML】</p>
	 * <p>条件:</p>
	 * <p>备注:</p>
	 * <p>例子:</p>
	 * <p>日志:</p>
	 *
	 * @author:zhu  [2016年1月29日 下午2:50:28]
	 */
	public void importDocToHtml() {
		//启动word
		ActiveXComponent axc = new ActiveXComponent("Word.Application");
		StringWriter stringWriter = null;
		try {
			// doc临时存放文件夹路径
			String realpath = ServletActionContext.getServletContext().getRealPath("/UserUploadFile/WordToHTML");
			File tempfile = null;
			if (docFile != null) {
				String tempName = String.valueOf((new Date()).getTime());
				tempfile = new File(new File(realpath), tempName + ".doc");
				//判断文件是否存在
				if (!tempfile.getParentFile().exists()) {
					//创建文件
					tempfile.getParentFile().mkdirs();
				}
				//copy文件的创建的文件上
				FileUtils.copyFile(docFile, tempfile);
				//设置word不可见
				axc.setProperty("Visible", new Variant(false));
				Dispatch docs = axc.getProperty("Documents").toDispatch();
				//打开word文档
				Dispatch doc = Dispatch.invoke(docs, "Open", Dispatch.Method,
						new Object[] { docFile.getPath(), new Variant(false), new Variant(true) }, new int[1])
						.toDispatch();
				String htmlUrl = tempfile.getPath().substring(0, tempfile.getPath().lastIndexOf(".") + 1) + "html";
				//作为html格式保存到临时文件
				Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] { htmlUrl, new Variant(8) }, new int[1]);
				//下方如果报错,去除f参数变量
				//0不保存修改 -1 保存修改 -2 提示是否保存修改 
				Variant f = new Variant(0);
				Dispatch.call(doc, "Close", f);
				//删除文件
				//FileUtils.forceDelete(tempfile);
				File file = new File(htmlUrl);
				//读取需要注意编码
				InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "gbk");
				BufferedReader br = new BufferedReader(isr);
				String s = null;
				StringBuffer html = new StringBuffer();
				while ((s = br.readLine()) != null) {//使用readLine方法,一次读一行
					html.append(s);
				}
				br.close();
				Map<String, Object> result = new HashMap<String, Object>();
				//因为一次读一行的原因,可以标签和属性之间没间隔,所以需要格式化
				result.put("html", formatHTML(html.toString(), tempName));
				// 操作成功的话,将文档id返回
				Struts2Utils.outJSON(result);
			}
		} catch (Exception e) {
			setErrMessage("导入Excel数据错误,请检查数据!");
		} finally {
			axc.invoke("Quit", new Variant[] {});
		}
	}
	/**
	 * 
	 * <p>【对当前html进行处理】</p>
	 * <p>条件:</p>
	 * <p>备注:如果有图片会在html同目录下生成一个存放图片的文件夹</p>
	 * <p>例子:</p>
	 * <p>日志:</p>
	 *
	 * @param html			html的内容
	 * @param htmlName		html文件名
	 * @return
	 * @author:zhu  [2016年2月3日 下午5:01:36]
	 */
	private String formatHTML(String html, String htmlName) {
		//截取出body中的内容
		html = html.substring(html.indexOf("body"), html.lastIndexOf("body"));
		html = html.substring(html.indexOf(">") + 1, html.lastIndexOf("<"));
		//对src、style、lang进行处理,可能和标签链接紧密
		html = html.replaceAll("src", "\t src").replaceAll("style", "\t style").replaceAll("lang", "\t lang");
		//图片需要真是的路径
		html = html.replaceAll(htmlName, "../../UserUploadFile/WordToHTML/" + htmlName);
		return html;
	}

三、前台实现

     前台主要一个上传,和获取html代码后直接赋值到编辑器上的功能。

    我使用uploadify实现上传,核心代码

$(function() {
		$("#fileUp").uploadify({
			swf				: '${request.contextPath}/resources/uploadify/uploadify.swf', 
			uploader		: 'hdAction!importDocToHtml.shtml',							// 用于接收上传文件的action
			auto			: true,									// 是否自动开始 上传
			buttonText		: '导入Word', 							// 按钮上的文字 
			debug			: false,								// 是否调试状态
			fileObjName		: 'docFile',							// action中的文件对象名
	 		fileSizeLimit	: (100*1024*1024), 						// 设置单个文件大小限制,单位为byte。设置为100m
			fileTypeDesc	: '支持格式:*.doc', 				// 如果配置了以下的'fileExt'属性,那么这个属性是必须的  
	 		fileTypeExts	: '*.doc',								// 允许的格式,如:*.jpg;*.gif;*.jpeg;*.png;*.bmp
			method          : 'post',								// 上传数据的方法
			multi			: true,									// 是否支持多文件上传 
			onUploadSuccess : function(file, data, response) {
				var result=$.parseJSON(data);
				//eWebEditor编辑器赋值
				$("#eWebEditor1").contents().find("body").find("#eWebEditor").contents().find("body").html(result.html);
			},
			onError: function(event, queueID, fileObj) {
				alert("文件:" + fileObj.name + "上传失败!");  
			},		
			onUploadError : function(file,errorCode,errorMsg,errorString,swfuploadifyQueue) {// 上传文件出错是触发(每个出错文件触发一次)
				alert( '上传文件出错,id: ' + file.id
						+ ' \r\n- 索引: ' + file.index
						+ ' \r\n- 文件名: ' + file.name
						+ ' \r\n- 文件大小: ' + file.size
						+ ' \r\n- 类型: ' + file.type
						+ ' \r\n- 创建日期: ' + file.creationdate
						+ ' \r\n- 修改日期: ' + file.modificationdate
						+ ' \r\n- 文件状态: ' + file.filestatus
						+ ' \r\n- 错误代码: ' + errorCode
						+ ' \r\n- 错误描述: ' + errorMsg
						+ ' \r\n- 简要错误描述: ' + errorString
						+ ' \r\n- 出错的文件数: ' + swfuploadifyQueue.filesErrored
						+ ' \r\n- 错误信息: ' + swfuploadifyQueue.errorMsg
						+ ' \r\n- 要添加至队列的数量: ' + swfuploadifyQueue.filesSelected
						+ ' \r\n- 添加至对立的数量: ' + swfuploadifyQueue.filesQueued
						+ ' \r\n- 队列长度: ' + swfuploadifyQueue.queueLength);
			},
			onCancel: function(event, queueID, fileObj){  
				//alert("取消了" + fileObj.name);  
			}
		});	
	})
<tr>
    	<th></th>
    	<td><input type='file' id='fileUp' name='fileUp' /></td>
  </tr>


展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
14 收藏
1
分享
返回顶部
顶部