前言
近日項目中做到一個功能,需要上傳附件後能夠線上預覽。之前也沒做過這類似的,於是乎就尋找了相關資料,.net實現Office檔案預覽大概有這幾種方式:
使用Microsoft的Office組件將檔案直接轉換為html檔案(優點:代碼實現最簡單,工作強度最小。缺點:效果極差)
使用Microsoft的Office組件將檔案轉換為PDF格式檔案,然後再使用pdf2swf轉換為swf檔案,也就是flash檔案在使用FlexPaper展示出來(優點:預覽效果能接受,缺點:代碼量大)
使用Office online(優點:表現完美,缺點:不適合中小公司專屬應用程式)
由於開發時間短而且還有其他功能點需要完成,所以暫時先已第一種方式實現了,這裡也主要講第一種方式,效果如:
具體實現
這裡簡單提一下中的遮罩效果和上傳實現,有喜歡的朋友也可以參考參考。
遮罩效果就是HTML+CSS+JS來實現的,全部代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>彈出層</title><script src="jquery-1.6.2.min.js" type="text/javascript"></script><style>.black_overlay{ display: none; position: absolute; top: 0%; left: 0%; width: 100%; height: 100%; background-color: black; z-index:1001; -moz-opacity: 0.8; opacity:.80; filter: alpha(opacity=80);}.white_content { display: none; position: absolute; top: 10%; left: 10%; width: 80%; height: 80%; border: 16px solid lightblue; background-color: white; z-index:1002; overflow: auto;}.white_content_small { display: none; position: absolute; top: 20%; left: 30%; width: 40%; height: 50%; border: 16px solid lightblue; background-color: white; z-index:1002; overflow: auto;}</style><script type="text/javascript">//彈出隱藏層function ShowDiv(show_div,bg_div){ document.getElementById(show_div).style.display='block'; document.getElementById(bg_div).style.display='block' ; var bgdiv = document.getElementById(bg_div); bgdiv.style.width = document.body.scrollWidth; // bgdiv.style.height = $(document).height(); $("#"+bg_div).height($(document).height());};//關閉彈出層function CloseDiv(show_div,bg_div){ document.getElementById(show_div).style.display='none'; document.getElementById(bg_div).style.display='none';};</script></head><body><input id="Button1" type="button" value="點擊彈出層" onclick="ShowDiv('MyDiv','fade')" /><!--彈出層時背景層DIV--><div id="fade" class="black_overlay"></div> <div id="MyDiv" class="white_content"> <div style="text-align: right; cursor: default; height: 40px;"> <span style="font-size: 16px;" onclick="CloseDiv('MyDiv','fade')">關閉</span> </div> 目前來說,我還是喜歡這個自己改造的彈出層。自己在項目中也用的是這個。 </div></body></html>
上傳的話,因為檔案比較小,所以採用的是儲存在伺服器,在資料庫中存放路徑的方式
前台代碼
<div class="white_content" id="MyDiv" style="text-align: center; display: none;"> <div style="text-align: right; cursor: default; height: 40px;"> <span style="font-size: 16px;" onclick="CloseDiv('MyDiv','fade')">關閉</span> </div> <tr style="width: 50%" id="upload_Image"> <h1> 請上傳常見問題附件</h1> <td align="right" class="Title"> 上傳附件 </td> <td> <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Label ID="label1" runat="server" ForeColor="Red"></asp:Label> <asp:Button ID="UploadButton" runat="server" Text="上傳附件" OnClick="UploadButton_Click" /> </td> </tr> <tr> <td colspan="2" align="center" id="show_image" style="visibility: hidden"> <asp:Image ID="Image1" runat="server" Height="118px" Width="131px" /> </td> </tr> </div>
後台方法
try { string FullName = FileUpload1.PostedFile.FileName;//擷取附件物理地址 FileInfo fi = new FileInfo(FullName); string name = fi.Name;//擷取附件名稱 string type = fi.Extension;//擷取附件類型 if (type == ".xls" || type == ".xlsx" || type == ".doc" || type == ".docx" || type == ".pdf") { string SavePath = Server.MapPath("~\\uploadFile");//附件儲存到檔案夾下 if (!Directory.Exists(SavePath)) { Directory.CreateDirectory(SavePath); } this.FileUpload1.PostedFile.SaveAs(SavePath + "\\" + name);//儲存路徑 #region 將附件內容儲存到資料庫中 int showsuccess = CMSModelManager.Submitted_questionsDAO.Save_File(name,type,SavePath); if (showsuccess == 1) { this.label1.Text = "上傳成功"; } else { this.label1.Text = "伺服器繁忙,請稍後重試"; } #endregion } else { this.label1.Text = "請選擇正確的格式附件"; } } catch (Exception ex) { Response.Write(ex.Message); }
圖中所示的將Word轉換成HTML的實現方式:
首先建立一個協助類
using System;using System.Collections.Generic;using System.Web;//using Microsoft.Office.Core;using Word = Microsoft.Office.Interop.Word;namespace Com.VanruPortal.Admin{ public class Office2HtmlHelper { /// <summary> /// Word轉成Html /// </summary> /// <param name="path">要轉換的文檔的路徑</param> /// <param name="savePath">轉換成html的儲存路徑</param> /// <param name="wordFileName">轉換成html的檔案名稱字</param> public static void Word2Html(string path, string savePath, string wordFileName) { Word.ApplicationClass word = new Word.ApplicationClass(); Type wordType = word.GetType(); Word.Documents docs = word.Documents; Type docsType = docs.GetType(); Word.Document doc = (Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { (object)path, true, true }); Type docType = doc.GetType(); string strSaveFileName = savePath + wordFileName + ".html"; object saveFileName = (object)strSaveFileName; docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, Word.WdSaveFormat.wdFormatFilteredHTML }); docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null); wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null); } /// <summary> /// Excel轉成Html /// </summary> /// <param name="path">要轉換的文檔的路徑</param> /// <param name="savePath">轉換成html的儲存路徑</param> /// <param name="wordFileName">轉換成html的檔案名稱字</param> public static void Excel2Html(string path, string savePath, string wordFileName) { string str = string.Empty; Microsoft.Office.Interop.Excel.Application repExcel = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook workbook = null; Microsoft.Office.Interop.Excel.Worksheet worksheet = null; workbook = repExcel.Application.Workbooks.Open(path, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; object htmlFile = savePath + wordFileName + ".html"; object ofmt = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml; workbook.SaveAs(htmlFile, ofmt, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); object osave = false; workbook.Close(osave, Type.Missing, Type.Missing); repExcel.Quit(); } }}
後台調用方法
上傳成功後將檔案轉換string physicalPath = Server.MapPath(Server.UrlDecode("/uploadFile"+"\\"+ name));//讀取相對路徑string extension = Path.GetExtension(physicalPath);//擷取尾碼名string[] show_name = name.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);//此處的name是上面上傳附件中的名稱分割string show_name_View = show_name[0];//拿到實際nameswitch (extension){ case ".doc": case ".docx": Office2HtmlHelper.Word2Html(MapPath("/uploadFile" + "\\" + name + ""), MapPath("/Html/"), "" + show_name_View + ""); //調用協助類中產生WordHtml的方法,並儲存起來 Response.Write("<script>window.open('/Html/" + show_name_View + ".html','_blank')</script>"); //跳轉並開啟儲存的相對路徑中hmtl檔案 break; case ".xls": case ".xlsx": Office2HtmlHelper.Excel2Html(MapPath("/uploadFile" + "\\" + name + ""), MapPath("/Html/"), "" + show_name_View + ""); Response.Write("<script>window.open('/Html/" + show_name_View + ".html','_blank')</script>"); break; default: break;}
至此,一個簡易的上傳附件線上瀏覽已經全部實現
以上就是.NET編程中Word/Excel 線上預覽的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!