Program.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Microsoft.Office.Interop.Word;
  6. using System.Runtime.InteropServices;
  7. namespace WordToHtml
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. var result = "C:\\Users\\CrazyIter\\Desktop\\导入异常试卷\\IES5-109指考最前線-化學科.docx";
  14. //var result = "C:\\Users\\CrazyIter\\Desktop\\IES5-109指考最前線-化學科.docx";
  15. //Word 转 Html
  16. //前提:请先引用 Microsoft.Office.Interop.Word
  17. ApplicationClass w_app = new ApplicationClass();
  18. Type wordType = w_app.GetType();
  19. Documents w_docs = w_app.Documents;
  20. Type docsType = w_docs.GetType();
  21. object p_file_nm = result; //请在d分区下先新建好这个文件
  22. object saveFileName = @"C:\Users\CrazyIter\Desktop\导入异常试卷\1111111\abcd.html";
  23. Document w_doc = (Microsoft.Office.Interop.Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, w_docs, new Object[] { p_file_nm, true, true }); new UnknownWrapper(null);
  24. Type docType = w_doc.GetType();
  25. docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, w_doc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML });
  26. wordType.InvokeMember("Quit",
  27. System.Reflection.BindingFlags.InvokeMethod,
  28. null,
  29. w_app,
  30. null
  31. );
  32. }
  33. /// <summary>
  34. /// word转成html
  35. /// </summary>
  36. /// <param name="wordFileName"></param>
  37. private string WordToHtml(object wordFileName)
  38. {
  39. //在此处放置用户代码以初始化页面
  40. Microsoft.Office.Interop.Word.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass();
  41. Type wordType = word.GetType();
  42. Documents docs = word.Documents;
  43. //打开文件
  44. Type docsType = docs.GetType();
  45. Document doc = (Document)docsType.InvokeMember("Open",
  46. System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { wordFileName, true, true });
  47. //转换格式,另存为
  48. Type docType = doc.GetType();
  49. string wordSaveFileName = wordFileName.ToString();
  50. string strSaveFileName = wordSaveFileName.Substring(0, wordSaveFileName.Length - 3) ;
  51. object saveFileName = (object)strSaveFileName;
  52. docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
  53. null, doc, new object[] { saveFileName, WdSaveFormat.wdFormatFilteredHTML });
  54. docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod,
  55. null, doc, null);
  56. //退出 Word
  57. wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod,
  58. null, word, null);
  59. return saveFileName.ToString();
  60. }
  61. }
  62. }