C #. NET converts Word or Excel files into HTML files,

Source: Internet
Author: User

C #. NET converts Word or Excel files into HTML files,

Convert Word files to html and return relative paths

1 private string GetPathByDocToHTML (string strFile) 2 {3 if (string. isNullOrEmpty (strFile) 4 {5 return "0"; // No file 6} 7 8 Microsoft. office. interop. word. applicationClass word = new Microsoft. office. interop. word. applicationClass (); 9 Type wordType = word. getType (); 10 Microsoft. office. interop. word. required ents docs = word. documents; 11 12 // open the file 13 Type docsType = docs. getType (); 14 15 object fileName = StrFile; 16 17 Microsoft. office. interop. word. document doc = (Microsoft. office. interop. word. document) docsType. invokeMember ("Open", 18 System. reflection. bindingFlags. invokeMethod, null, docs, new Object [] {fileName, true, true}); 19 20 // conversion format, saved as html 21 Type docType = doc. getType (); 22 // rename the file 23 string filename = System. dateTime. now. year. toString () + System. dateTime. now. month. toString () + System. DateTime. now. day. toString () + 24 System. dateTime. now. hour. toString () + System. dateTime. now. minute. toString () + System. dateTime. now. second. toString (); 25 26 string strFileFolder = ".. /html/"; 27 DateTime dt = DateTime. now; 28 // The Child folder name is 29 string strFileSubFolder = dt in the form of yyyymmdd. year. toString (); 30 strFileSubFolder + = (dt. month <10 )? ("0" + dt. Month. ToString (): dt. Month. ToString (); 31 strFileSubFolder + = (dt. Day <10 )? ("0" + dt. day. toString (): dt. day. toString (); 32 string strFilePath = strFileFolder + strFileSubFolder + "/"; 33 // determines whether a folder exists in the specified directory. if not, create 34 if (! Directory. exists (Server. mapPath (strFilePath) 35 {36 // create up folder 37 Directory. createDirectory (Server. mapPath (strFilePath); 38} 39 40 // location where the converted html document is saved 41 // HttpContext. current. server. mapPath ("html" + strFileSubFolder + filename + ". html ") 42 string ConfigPath = Server. mapPath (strFilePath + filename + ". html "); 43 object saveFileName = ConfigPath; 44 45/* The following is the Microsoft Word 9 Object Library statement. If it is 10, it may be written as 46 * docType. invokeMember ("SaveAs", System. reflection. bindingFlags. invokeMethod, 47 * null, doc, new object [] {saveFileName, Word. wdSaveFormat. wdFormatFilteredHTML}); 48 * Other formats: 49 * wdFormatHTML 50 * wdFormatDocument 51 * wdFormatDOSText 52 * unique 53 * wdFormatEncodedText 54 * wdFormatRTF 55 * wdFormatTemplate 56 * wdFormatText 57 * wdFormatTextLineBreaks 58 * wdFormatUnicodeText 59 */60 docType. invokeMember ("SaveAs", System. reflection. bindingFlags. invokeMethod, 61 null, doc, new object [] {saveFileName, Microsoft. office. interop. word. wdSaveFormat. wdFormatFilteredHTML}); 62 63 // docType. invokeMember ("SaveAs", System. reflection. bindingFlags. invokeMethod, 64 // null, doc, new object [] {saveFileName, Microsoft. office. interop. word. wdSaveFormat. wdFormatFilteredHTML}); 65 66 // close doc67 docType. invokeMember ("Close", System. reflection. bindingFlags. invokeMethod, 68 null, doc, new object [] {null, null, null}); 69 70 // exit Word 71 wordType. invokeMember ("Quit", System. reflection. bindingFlags. invokeMethod, null, word, null); 72 // go to the newly generated Page 73 // return ("/" + filename + ". html "); 74 75 // convert the unified HTML page encoding format 76 TransHTMLEncoding (ConfigPath); 77 78 return (strFilePath + filename + ". html "); 79}

Convert the Excel file to HTML and return the relative path

1 private string GetPathByXlsToHTML (string strFile) 2 {3 if (string. isNullOrEmpty (strFile) 4 {5 return "0"; // No file 6} 7 8 // instantiate Excel 9 Microsoft. office. interop. excel. application repExcel = new Microsoft. office. interop. excel. application (); 10 Microsoft. office. interop. excel. workbook workbook = null; 11 Microsoft. office. interop. excel. worksheet worksheet = null; 12 13 // open the file, n. fullPath is the file path 14 workbook = RepExcel. application. workbooks. open (strFile, 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); 15 worksheet = (Microsoft. office. interop. excel. worksheet) workbook. worksheets [1]; 16 17 // rename the file 18 string filename = System. dateTime. now. year. toString () + Sy Stem. dateTime. now. month. toString () + System. dateTime. now. day. toString () + 19 System. dateTime. now. hour. toString () + System. dateTime. now. minute. toString () + System. dateTime. now. second. toString (); 20 21 string strFileFolder = ".. /html/"; 22 DateTime dt = DateTime. now; 23 // generate the sub-Folder name in the form of yyyymmdd 24 string strFileSubFolder = dt. year. toString (); 25 strFileSubFolder + = (dt. month <10 )? ("0" + dt. Month. ToString (): dt. Month. ToString (); 26 strFileSubFolder + = (dt. Day <10 )? ("0" + dt. day. toString (): dt. day. toString (); 27 string strFilePath = strFileFolder + strFileSubFolder + "/"; 28 // you can check whether a folder exists in the specified directory. if not, create 29 if (! Directory. exists (Server. mapPath (strFilePath) 30 {31 // create up folder 32 Directory. createDirectory (Server. mapPath (strFilePath); 33} 34 string ConfigPath = Server. mapPath (strFilePath + filename + ". html "); 35 object savefilename = (object) ConfigPath; 36 37 object ofmt = Microsoft. office. interop. excel. xlFileFormat. xlHtml; 38 // save as 39 workbook. saveAs (savefilename, 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); 40 object osave = false; 41 // gradually close all used objects 42 workbook. close (osave, Type. missing, Type. missing); 43 repExcel. quit (); 44 System. runtime. interopServices. marshal. releaseComObject (worksheet); 45 worksheet = null; 46 // garbage collection 47 GC. collect (); 48 System. runtime. interopServices. marshal. releaseComObject (workbook); 49 workbook = null; 50 GC. collect (); 51 System. runtime. interopServices. marshal. releaseComObject (repExcel. application. workbooks); 52 GC. collect (); 53 System. runtime. interopServices. marshal. releaseComObject (repExcel); 54 repExcel = null; 55 GC. collect (); 56 // kill the process 57 System Based on time. diagnostics. process [] process = System. diagnostics. process. getProcessesByName ("EXCEL"); 58 foreach (System. diagnostics. process p in process) 59 {60 if (DateTime. now. second-p. startTime. second> 0 & DateTime. now. second-p. startTime. second <5) 61 {62 p. kill (); 63} 64} 65 66 return (strFilePath + filename + ". html "); 67}

Here, you may encounter a problem. Because the Page code converted to an HTML file may make the browser unable to interpret it correctly, transcoding is required. The conversion code is as follows:

 1     private void TransHTMLEncoding(string strFilePath) 2     { 3         try 4         { 5             System.IO.StreamReader sr = new System.IO.StreamReader(strFilePath, Encoding.GetEncoding(0)); 6             string html = sr.ReadToEnd(); 7             sr.Close(); 8             html = System.Text.RegularExpressions.Regex.Replace(html, @"<meta[^>]*>", "<meta http-equiv=Content-Type content='text/html; charset=gb2312'>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); 9             System.IO.StreamWriter sw = new System.IO.StreamWriter(strFilePath, false, Encoding.Default);10 11             sw.Write(html);12             sw.Close();13         }14         catch (Exception ex)15         {16             Page.RegisterStartupScript("alt", "<script>alert('" + ex.Message + "')</script>");17         }18     }

In this way, the page is displayed normally.

 

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.