doc和docx格式是無法直接在瀏覽器中顯示的,需要轉換為瀏覽器支持的格式,方法如下:
1、打開需要轉換的文件,點擊文件選擇另存為;
2、選擇保存的格式為單個網頁(*.mht ,*.mhtl)、網頁(*.hmt ,*.hmtl )或者篩選過的網頁(*.hmt ,*.hmtl )即可。
把word文件讀到byte[]中,再Response.OutputStream.Write(bytes)到客戶端去
Page_Load事件中寫:
//FileStream fs = new FileStream("c:\\1.doc", FileMode.Open, FileAccess.Read); FileStream fs = new FileStream(Server.MapPath("files\\1.doc"),FileMode.Open, FileAccess.Read);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/msword";
//Response.OutputStream(bytes);
Response.OutputStream.Write(bytes,0, bytes.Length);
Response.End();
在網頁中顯示.txt文件的內容:
直接就可以顯示,如果想放到表格中,可以<iframe src="XXX.txt"></iframe>
word文件也可以照此。
為了正確處理word等格式,你需要在HTML文件中設置好該文件類型,比如:
<meta http-equiv="Content-Type" content="Application/msword">
還有其它經常設置的文件類型:
Application/msword Microsoft Word Document
application/pdf PDF Document
application/wordperfect6.0 WordPerfect 6.0 Document
application/zip ZIP archive
audio/x-wav WAV audio format
audio/midi MIDI audio format
audio/x-pn-realaudio RealAudio
image/gif GIF image format
image/jpeg JPEG image format
image/png PNG image format
text/html HTML document
text/plain Plain text
video/mpeg MPEG video format
video/quicktime QuickTime video format
video/x-msvideo AVI video format
文章來源於易賢網http://www.ynpxrz.com/n765461c2023.aspx
還有一種,做參考
response.setContentType("application/vnd.ms-excel");
File file =new File("D:/test.xls");
FileInputStream in=new FileInputStream(file);
byte[] buffer=new byte[in.available()];
in.read(buffer);
response.getOutputStream().write(buffer);
response.getOutputStream().flush();
這篇文章主要是圍繞如何實現Word文檔在頁面上進行預覽,以及涉及到相關的技術點,和我們將會在這個功能上使用的插件。
插件:Aspose.Total:
Aspose.Total是Aspose公司旗下的最全的一套office文檔管理方案,主要提供.net跟java兩個開發語言的控件套包,通過它,我們可以有計划地操縱一些商業中最流行的文件格式:Word, Excel, PowerPoint, Project,等office文檔以及PDF文檔。
在這個功能模塊中我們只使用其中的一個強大的類庫:Aspose.Words:
Aspose.Words是一款先進的類庫,通過它可以直接在各個應用程序中執行各種文檔處理任務。Aspose.Words支持DOC,OOXML,RTF,HTML,OpenDocument, PDF, XPS, EPUB和其他格式。使用Aspose.Words,您可以生成,更改,轉換,渲染和打印文檔而不使用Microsoft Word。
上硬貨( 前台代碼):
<div id="WordPreview"> <div class="panel panel-info " id="panel1"> <div class="panel-heading"> <h3 class="panel-title">Word瀏覽</h3> </div> <div id="main"> <div id="content"> <div id="contents"> <iframe id="myFrame" name="_blank" frameborder="0" scrolling="no" onload="this.height=myFrame.document.body.scrollHeight"></iframe> </div> </div> <div class="col-sm-12 padding-t-5" > <div id="name" class="col-sm-6"></div> <div id="date" class="col-sm-6"></div> </div> </div> </div> </div>
這里我們會使用HTML5 的 iframe 標簽:
iframe 標簽規定一個內聯框架,一個內聯框架被用來在當前 HTML 文檔中嵌入另一個文檔,我們將會把Word文檔的內容在這個Iframe中顯示出來。
JS:
我這里的邏輯是首先選中一個文檔觸發預覽事件,所以我需要有一條這樣的代碼:
var DocID = getQueryString("DocID"); function getQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]); return null; }
其次我需要向后台發送獲取文檔和處理文檔的請求:
function Preview(id) { var formData = new FormData(); $.ajax({ type: "post", url: '../Test.ashx?action=TestPreview&DocID=' + DocID, async: false, dataType: "json", data: formData, contentType: false, processData: false, success: function (result) { var dataStr = result.Data.split('|'); if (dataStr[0] != "0") { $('#name').text(dataStr[1]); document.getElementById('myFrame').src = '../WordFile' + dataStr[0] + '.html'; $('#date').text(dataStr[2]); myStyle(); YLID = dataStr[0]; } }, }); }
最后給我們的顯示框設置一下高度和寬度
function myStyle() { $("#main").width(960); $("#main").height($('#WordPreview').height() - 100); $('#content').height($('#main').height() - 50); $('#myFrame').width(580); }
現在后台已經拿到我們的請求,並且根據url 解析出我們需要調用的方法
action:TestPreview 和 DocID:DocID。
下面的代碼省略了try,catch,只展示了Try中的代碼:
//從Session中獲取用戶基本信息 BLL.User user = context.Session["User"] as BLL.User; string id = context.Request["DateID"]; int userId = user.UserID; string sql = ""; string ext = ""; string docName = ""; string submitDate = ""; byte[] bytes = { }; //打開並連接數據庫 DBAccess DBA = new DBAccess(); sql = string.Format(@"SELECT DocName,Length,IOStream,ModifyTime FROM dbo.TestWordInfo WHERE ID={0}", id); //獲取文檔的詳細數據,包括保存在SQL中的文件二進制流 DataTable dt = DBA.GetDataTable(sql); if (dt.Rows.Count > 0) { bytes = new byte[int.Parse(dt.Rows[0]["Length"].ToString())]; //判斷是doc還是docx ext = dt.Rows[0]["DocName"].ToString().EndsWith(".doc") ? ".doc" : ".docx"; //將二進制流保存在byte[]數組中 bytes = (byte[])dt.Rows[0]["IOStream"]; string[] docStr = dt.Rows[0]["DocName"].ToString().Split('.'); docName = docStr[0]; } if (bytes.Length > 0) { //這一步就是具體的格式轉制過程(將在下面代碼進行分析解釋) putFile(context, bytes, id, ext); } else { id = "0"; } result = id + "|" + docName + "|" + submitDate;
這里我們基本上已經完成了一大半了,成功的把數據從數據庫中讀取出來了,接下來我們就會對這些數據進行相應的解析處理,使它們能夠滿足我們的需要在頁面中進行展示。
//傳入四個基本參數 public void putFile (HttpContext context, byte[] bytes, string id, String ext) { try { //根據相對路徑創建臨時文件目錄 string savePath = context.Server.MapPath("~/WeekReport/"); if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } //向空的文件中寫入數據流 using (FileStream fs = new FileStream(savePath + id + ext, FileMode.Create)) { fs.Write(bytes, 0, bytes.Length); } //使用Aspose.Words的功能配合"Save"進行Word文檔到HTML頁面的轉制工作 Aspose.Words.Document doc = new Aspose.Words.Document(savePath + id + ext); HtmlSaveOptions hso = new HtmlSaveOptions(SaveFormat.Html); string htmlPath = savePath + id + ".html"; doc.Save(htmlPath, hso); //轉制完成后,刪除原有的Word文件 DeleteFile(savePath + id + ext); } catch (Exception ex) { throw ex; } public static void DeleteFile(string fileUrl) { if (System.IO.File.Exists(fileUrl)) { System.IO.File.Delete(fileUrl); } } }