Excel spell check using C#

前端 未结 2 1135
旧时难觅i
旧时难觅i 2021-01-27 01:13

some one just help me with this! why isn\'t this code working.I don\'t find much tutorials on the internet too.

Excel.Application xlApp;
Excel.Workbook xlWorkBoo         


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-27 01:35

    I think you might want to check out the APIs on MSDN, here's the links =>
    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

    According to the definition, CheckSpelling method does this, "Checks the spelling of a single word. Returns True if the word is found in one of the dictionaries; returns False if the word isn't found."

    That means, if any word is misspelled, CheckSpelling should return False (depends on whether the word is in the given dictionary or not)

    In your code, you were doing

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

    which I think is the opposite to what you were trying to achieve. ("have the string "chk" in the cell besides every wrongly spelled word")

    So just add ! to your if statement

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

    and that should be what you were after.

    Also, for code clarity and readability, I'd highly suggest that you break down your code into functions, methods, etc. And be careful about calling xlWorkSheet.Cells[k+2, 1].ToString(), as it might give you Null exception without checking the value first.

提交回复
热议问题