Excel拼写检查使用C#

有人只是帮助我这个! 为什么不是这个代码工作。我也没有在互联网上find太多的教程。

Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value; xlApp = new Excel.ApplicationClass(); xlWorkBook = xlApp.Workbooks.Add(misValue); xlWorkShee=(Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); xlApp.SpellingOptions.UserDict = "CUSTOM.DIC"; var udict = xlApp.SpellingOptions.UserDict; xlWorkSheet.CheckSpelling(); xlWorkSheet.Cells[1, 1] = "Sstring"; string tsql = "select nvalue from [role report]"; OleDbDataAdapter tda = new OleDbDataAdapter(tsql, con); DataTable tdt = new DataTable(); con.Open(); tda.Fill(tdt); con.Close(); int count = 0; for (int x = 0; x<500; x++) { if (tdt.Rows[x]["nvalue"].ToString()!= "") { xlWorkSheet.Cells[x+2, 1] = tdt.Rows[x]["nvalue"].ToString(); count++; } } for (int k=0; k<count; y++) { //bool t = false; if (xlWorkSheet.Cells[k+2, 1].ToString() != "") { if ((xlApp.CheckSpelling(xlWorkSheet.Cells[k+2, 1].ToString()))) xlWorkSheet.Cells[k+2, 2] = "chk"; } } try { xlWorkBook.SaveAs("spellspell.xls",Excel.XlFileFormat.xlWorkbookNormal, misValue,Excel.XlSaveAsAccessMode.xlExclusive,misValue, misValue, misValue,misValue,misValue); } catch (Exception ex) { } xlWorkBook.Close(true, misValue, misValue); xlApp.Quit(); releaseObject(xlWorkSheet); releaseObject(xlWorkBook); releaseObject(xlApp); MessageBox.Show("Excel file created, you can find the file c:\\csharp-Excel.xls") 

除了每个拼写错误的单词外,我的输出应该在单元格中包含string“chk”。 但是输出不显示。

这个代码终于为我工作了! 从Access Db中取出数据并将其作为列存储在Excel中,并使用代码在Excel表格中识别拼写错误的单词。

  for (int y = 0; y <count; y++) { try { if(xlWorkSheet.Range["A" + (y + 2) + ""].Value.ToString() != "") { if (!(xlApp.CheckSpelling(xlWorkSheet.Range["A" + (y + 2) + ""].Value.ToString(), udict, 1033))) { xlApp.Visible = false; xlWorkSheet.Cells[y + 2, 2] = "chk"; } } } catch(Exception) { } } 

细胞的select是让我忙碌的部分。 最后

  if (!(xlApp.CheckSpelling(xlWorkSheet.Range["A" + (y + 2) + ""].Value.ToString(), udict, 1033))) 

工作。 它显示了“chk”针对每个错误的拼写单词。

我想你可能想查看MSDN上的API,这里是链接=>
Worksheet.CheckSpelling:
http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.worksheet.checkspelling(v=vs.100).aspx

Application.CheckSpelling:
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel._application.checkspelling

根据定义,CheckSpelling方法执行此操作:“检查单个单词的拼写,如果在其中一个词典中find该单词,则返回True ;如果未find该单词,则返回False

这意味着,如果任何单词拼写错误,CheckSpelling应返回False (取决于单词是否在给定的字典中)

在你的代码中,你在做

 if ((xlApp.CheckSpelling(xlWorkSheet.Cells[k+2, 1].ToString()))) xlWorkSheet.Cells[k+2, 2] = "chk"; 

我认为这与你试图达到的目的是相反的。 ( "have the string "chk" in the cell besides every wrongly spelled word"

所以只需添加! 到你的if语句

 if (!(xlApp.CheckSpelling(xlWorkSheet.Cells[k+2, 1].ToString()))) xlWorkSheet.Cells[k+2, 2] = "chk"; 

那应该是你以后的样子。

此外,为了代码的清晰性和可读性,我强烈build议你将代码分解成函数,方法等。并且要小心调用xlWorkSheet.Cells[k+2, 1].ToString() ,因为它可能会给你没有检查值的第一个空exception。