在實際開發過程中,經常會遇到在頁面上直接顯示word文檔的內容,當然這裡僅僅涉及到查看文檔內容,不涉及修改和儲存操作,這裡是利用Office的COM組件,將word文檔轉換程html格式後顯示在頁面中,html頁面中顯示的風格幾乎跟word內容一致。
補充說明:
代碼中使用了類庫dll檔案,及操作的DM類,這裡提供下載dll的地址:http://d.download.csdn.net/down/3499114/taomanman
和DM.cs類得代碼,放在App_Code目錄下即可。
using System;using System.Configuration;using System.Data;namespace USTC{ /// <summary> /// 串連sql資料庫。 /// </summary> public class DM { public USTC.SqlDbc db; public DM() { // // TODO: 在此處添加建構函式邏輯 // db = new USTC.SqlDbc(ConfigurationSettings.AppSettings["ConnectionString"]); //db.open(ConfigurationSettings.AppSettings["ConnectionString"]); } public USTC.SqlDbc getDataBase() { return db; } public DataSet getTable(string tablename) { db.open(); string tmpstr = "select * from " + tablename; DataSet result = (DataSet)db.getData(tmpstr, false); db.close(); return result; } public void deleteTable(string tablename) { db.open(); string tmpstr = "drop table " + tablename; db.getData(tmpstr, false); db.close(); } public int execsql1(string sql) { db.open(); int result = (int)db.getData(sql, false); db.close(); return result; } public void execsql(string sql) { db.open(); db.getData(sql, false); db.close(); } public DataSet getsql(string sql) { db.open(); DataSet result = (DataSet)db.getData(sql, false); db.close(); return result; } public static string Database2String(object data, int bz, string format) { string data1 = data.ToString(); switch (bz) { case 1: //數字 double d = 0; data1 = (double.TryParse(data1, out d) ? d.ToString(format) : ""); break; case 2://日期 DateTime dt = DateTime.Now; data1 = (DateTime.TryParse(data1, out dt) ? dt.ToString(format) : ""); break; default://字串 break; } return data1; } public static string Database2String(object data, int bz) { switch (bz) { case 1: //數字 return Database2String(data, bz, ""); case 2://日期 return Database2String(data, bz, "yyyy-MM-dd"); default://字串 return Database2String(data, bz, ""); } } public static DateTime Database2String(string date) { DateTime dt = Convert.ToDateTime(date); string time = dt.ToString("yyyy-MM-dd"); DateTime dt1 = Convert.ToDateTime(time); return dt1; } }}
這裡介紹一種可行的方案:
1、首先在項目引用中添加如下引用:
2、假如在項目根目錄下有一個專門的檔案夾,譬如叫UpLoad的檔案夾,專門用來存放上傳上來的Word文檔,這裡是在資料庫中儲存有檔案名稱的檔案存放目錄。
3、建立一個Default.aspx頁面,用於類比參數傳遞
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="FHGC_CZFH_Default" %><br /><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><br /><html xmlns="http://www.w3.org/1999/xhtml"><br /><head runat="server"><br /> <title></title><br /></head><br /><body><br /> <form id="form1" runat="server"><br /> <div><br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="查看word文檔" /><br /> </div><br /> </form><br /></body><br /></html>
using System;<br />using System.Collections.Generic;<br />using System.Linq;<br />using System.Web;<br />using System.Web.UI;<br />using System.Web.UI.WebControls;<br />public partial class FHGC_CZFH_Default : System.Web.UI.Page<br />{<br /> protected void Page_Load(object sender, EventArgs e)<br /> {<br /> }<br /> protected void Button1_Click(object sender, EventArgs e)<br /> {<br /> Response.Redirect("CountyTown.aspx?space=" + Server.UrlEncode("江潭鄉"));<br /> }<br />}
4、在CountyTown.aspx頁面中接受參數並做word轉html處理並顯示html頁面
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><br /><html xmlns="http://www.w3.org/1999/xhtml"><br /><head runat="server"><br /> <title>城鎮防洪預案</title><br /></head><br /><body><br /> <form id="form1" runat="server"><br /> </form><br /></body><br /></html>
using System;<br />using System.Collections.Generic;<br />using System.Linq;<br />using System.Web;<br />using System.Web.UI;<br />using System.Web.UI.WebControls;<br />using Microsoft.Office.Core;<br />using System.IO;<br />using USTC;<br />public partial class FHGC_CZFH_CountyTown : System.Web.UI.Page<br />{<br /> public string countyName = string.Empty; //鄉鎮名稱<br /> public string documentFullName = string.Empty; //預案全稱(包括尾碼名)<br /> public string documentName = string.Empty; //預案名稱<br /> protected void Page_Load(object sender, EventArgs e)<br /> {<br /> if (!IsPostBack)<br /> {<br /> try<br /> {<br /> //根據傳遞過來的鄉鎮名稱擷取到檔案名稱<br /> countyName = Server.UrlDecode(Request.QueryString["space"].ToString().Trim());<br /> DM dm = new DM();<br /> string strSQL = "select 預案檔案 from 山洪防治預案 where 鄉鎮名稱='" + countyName + "'";<br /> documentFullName = dm.getsql(strSQL).Tables[0].Rows[0]["預案檔案"].ToString().Trim();<br /> documentName = documentFullName.Substring(0, documentFullName.LastIndexOf('.'));<br /> }<br /> catch (Exception)<br /> {<br /> documentFullName = "";<br /> }<br /> }<br /> // 在此處放置使用者代碼以初始化頁面<br /> Word.ApplicationClass word = new Word.ApplicationClass();<br /> Type wordType = word.GetType();<br /> Word.Documents docs = word.Documents; // 開啟檔案<br /> Type docsType = docs.GetType();<br /> object fileName = Server.MapPath("~/Upload/") + documentFullName;<br /> Word.Document doc = (Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { fileName, true, true }); // 轉換格式,另存新檔<br /> Type docType = doc.GetType();<br /> object saveFileName = Server.MapPath("~/Upload/") + documentName+".html";<br /> ClientScript.RegisterClientScriptBlock(GetType(),"","<mce:script type="text/javascript"><!--<br />alert('"+saveFileName.ToString()+"');<br />// --></mce:script>");</p><p> //儲存HTML<br /> docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, Word.WdSaveFormat.wdFormatHTML });<br /> // 退出 Word<br /> wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);<br /> //跳轉顯示預案資訊<br /> Response.Redirect("~/Upload/" + documentName+".html");<br /> }<br />}
5、經過如上處理以後,在Word所在位置會產生一個檔案夾和一個同名的html檔案,我們要顯示的就是這個html的內容,如
6、大功告成,看一下:
點擊按鈕以後,可以查看Word文檔轉換程html後的內容了,如
基本上可以滿足一般的查看需求了,簡陋之篇,歡迎拍磚,共同探討,共同進步。