C# 利用 Word 實作拼字建議清單

C# 利用 Word 實作拼字建議清單

C# 利用 Word 實作拼字建議清單

加入參考 COM元件 Microsoft Word 12.0 Object Library

命名空間 using Microsoft.Office.Interop.Word;

  1. public string SpellCheck( string strSource)
  2. {
  3. StringBuilder strResult = new StringBuilder( );
  4. _Application objWord = new Microsoft.Office.Interop.Word.Application ( );
  5. ProofreadingErrors objErrors;
  6. SpellingSuggestions wdSuggestions;
  7. object t = Missing.Value;
  8. object nt = Missing.Value;
  9. object dt = Missing.Value;
  10. object v = true;
  11. Document objDocument = objWord.Documents.Add ( ref t, ref nt, ref dt, ref v);
  12. objWord.Selection.TypeText (strSource);
  13. objErrors = objDocument.SpellingErrors;
  14. if (objErrors.Count != 0 )
  15. {
  16. foreach (Range objError in objErrors)
  17. {
  18. object cd = Missing.Value;
  19. object iu = Missing.Value;
  20. object md = Missing.Value;
  21. object sm = Missing.Value;
  22. object cd2 = Missing.Value;
  23. object cd3 = Missing.Value;
  24. object cd4 = Missing.Value;
  25. object cd5 = Missing.Value;
  26. object cd6 = Missing.Value;
  27. object cd7 = Missing.Value;
  28. object cd8 = Missing.Value;
  29. object cd9 = Missing.Value;
  30. object cd10 = Missing.Value;
  31. wdSuggestions = objWord.GetSpellingSuggestions (objError.Text,
  32. ref cd, ref iu, ref md, ref sm, ref cd2, ref cd3, ref cd4,
  33. ref cd5, ref cd6, ref cd7, ref cd8, ref cd9, ref cd10);
  34. if (wdSuggestions.Count < 1 )
  35. {
  36. strResult.Append ( "無拼字建議!" );
  37. }
  38. else
  39. {
  40. int intCounter = 0;
  41. foreach (SpellingSuggestion wdSuggestion in wdSuggestions)
  42. {
  43. intCounter++;
  44. strResult.Append (wdSuggestion.Name );
  45. if (intCounter < wdSuggestions.Count )
  46. {
  47. strResult.Append ( "," );
  48. }
  49. }
  50. }
  51. }
  52. }
  53. else
  54. {
  55. strResult.Append ( "無拼字錯誤!" );
  56. }
  57. object sc = 0;
  58. object of = Missing.Value;
  59. object rd = Missing.Value;
  60. objWord.Quit ( ref sc, ref of, ref rd);
  61. objErrors = null;
  62. wdSuggestions = null;
  63. objDocument = null;
  64. objWord = null;
  65. return strResult.ToString ( );
  66. }