Asp. net method to convert Word files to HTML

  • 2020-12-26 05:38:11
  • OfStack

In this paper, an ES1en. net implements the function of converting Word to HTML. The key codes are as follows:


// store word The full path to the file 
 string wordPath = Server.MapPath("/word/test.doc");
 // store html The full path to the file 
 string htmlPath = Server.MapPath("/html/test.html");
 // upload word file ,  Because I'm just doing an example, I won't do much here to determine the file type, size, format, or existence of the file 
 FileUpload1.SaveAs(wordPath);
 #region  File format conversion 
 // Please refer to Microsoft.Office.Interop.Word
 ApplicationClass word = new ApplicationClass();
Type wordType = word.GetType();
Documents docs = word.Documents;

 // Open the file 
 Type docsType = docs.GetType();
 object fileName = wordPath; 
 //"f:\\cc.doc";
 Document doc =(Document)docsType.InvokeMember("Open", BindingFlags.InvokeMethod, null, (object)docs, new Object[] { fileName, true, true});

 // Determines whether a file associated with a file transformation exists, and deletes it if it does. Here, it's better to judge 1 Whether the directory under which the file is stored exists, or not, it is created) 
 if(File.Exists(htmlPath)) { File.Delete(htmlPath); }
 // every 1 a html File, 1 A corresponding storage html Folders for related elements (html The file name .files)
 if(Directory.Exists(htmlPath.Replace(".html" ,".files")))  
 { 
  Directory.Delete(htmlPath.Replace(".html", ".files"), true);
 };

 // Convert format, call word The "save as" method 
 Type docType =doc.GetType();
 object saveFileName = htmlPath; 
 //"f:\\aaa.html";
 docType.InvokeMember("SaveAs", BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, WdSaveFormat.wdFormatHTML });
 // exit  Word
 wordType.InvokeMember("Quit", BindingFlags.InvokeMethod, null, word, null);
 #endregion

The above code, in.net framework4.0, may issue a 1 compile error, as shown below:
Cannot embed interop type "..." , please use the appropriate interface.

After consulting materials, we found the following solutions:
Select dll to introduce word in the project, right-click, select Properties, and set the "Embedded Interop Type" to False.

Click here to download the complete code.


Related articles: