. NET programming in Word/excel online preview

Source: Internet
Author: User
Objective


Recently the project to do a function, you need to upload the attachment can be online preview. I've never done this before, so I've looked for relevant data, and. NET implements Office file previews in several ways:

    1. Use Microsoft Office components to convert files directly to HTML files (advantage: Code implementation is the simplest, the work intensity is minimal.) Disadvantage: very poor effect)

    2. Convert a file to a PDF file using Microsoft Office components, and then use pdf2swf to convert to a SWF file, that is, the Flash file is displayed using Flexpaper (Pros: The preview effect is acceptable, the disadvantage: The code size is large)

    3. Using Office Online (Pros: Performance Perfect, Cons: not suitable for SMB applications)

Because the development time is short and there are other function points need to be completed, so the first way is implemented, and here is mainly the first way, the effect such as:

Specific implementation

Here to briefly mention the mask effect and upload implementation, have a favorite friend can also refer to the reference.

The mask effect is HTML+CSS+JS, and the entire code is as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

Upload the words, because the file is relatively small, so the use is saved in the server, the way to store the path in the database

Front Code

<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 ')" > Close </span> &lt ;/div> <tr style= "width:50%" id= "upload_image" > 

Background methods

try {string FullName = fileupload1.postedfile.filename;//Gets the attachment physical Address FileInfo fi = new Fileinf                O (FullName); String name = Fi. name;//Gets the attachment name string type = Fi. extension;//Gets the attachment type if (type = = ". xls" | | type = = ". xlsx" | | type = = ". Doc" | | type = = ". docx" | | type = = ".                    PDF ") {string savepath = Server.MapPath (" ~\\uploadfile ");//attachments are saved to a folder if (!                    Directory.Exists (Savepath)) {directory.createdirectory (Savepath); } this. FileUpload1.PostedFile.SaveAs (Savepath + "\" + name);//save path #region Save the contents of the attachment to the database in                    T showsuccess = CMSModelManager.Submitted_questionsDAO.Save_File (Name,type,savepath);                    if (showsuccess = = 1) {This.label1.Text = "upload succeeded";                   } else {this.label1.Text = "server busy, please retry later";  } #endregion} else {This.label1.Text                = "Please select the correct format attachment"; }} catch (Exception ex) {Response.Write (ex).            Message); }

The implementation of converting Word to HTML is shown in the figure:

Create a new helper class first

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 {//<summa        ry>///Word to HTML//</summary>//<param name= "path" > Path of document to be converted </param> <param name= "Savepath" > Convert to HTML save path </param>//<param name= "Wordfilename" > converted to HTML file name < /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 to HTML///</summary>//<param name= "path" > document to convert Path </param>///<param Name= "Savepath" > Convert to HTML save path </param>//<param name= "Wordfilena        Me "> Convert HTML file name </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 (); }    }}

Background Call method

After the upload succeeds, convert the file to string physicalpath = Server.MapPath (Server.urldecode ("/uploadfile" + "\ \" + name);//Read relative path string extension = Path.getextension (PhysicalPath);//Gets the suffix name string[] show_name = name. Split (new string[] {"."}, stringsplitoptions.removeemptyentries);//The name here is the names in the upload attachment above split string Show_name_view = Show_ name[0];//get the actual nameswitch (extension) {case ". doc": Case ". docx": office2htmlhelper.word2html (MapPath ("/uplo      Adfile "+" \ "+ name +" "), MapPath ("/html/")," + Show_name_view + ""); Call the Help class to generate the Wordhtml method and save it Response.Write ("<script>window.open ('/html/" + Show_name_view + ". Html ', ' _blank ')      </script> ");     Jump and open Save relative path in HMTL file break; Case '. xls ': Case '. xlsx ': office2htmlhelper.excel2html (MapPath ("/uploadfile" + "\" + name + ""), MapPath ("/h     Tml/")," "+ Show_name_view +" ");       Response.Write ("<script>window.open ('/html/" + Show_name_view + ". Html ', ' _blank ') </script>");     Break Default:break;} 

At this point, a simple upload attachment online Browsing has been fully implemented


The above is. NET programming Word/excel online preview content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.