Monday, June 24, 2024

C# - Find Error Code in Excel Table using ClosedXML

 ClosedXML is a good choice for working with Excel files in C#. Here's a refined approach to achieve your goal:

 * Read Error Code: Prompt the user to enter the error code using textBox1.Text.


 * Open Excel File: Use XLWorkbook to open the Excel file ("C:\\Users\\admin\\Desktop\\VSC-500.xlsx").

 * Find Error in Table:

   * Iterate through each row in the worksheet.

   * Check if the value in a specific column (e.g., column B) matches the error code.

 * Display Explanation:

   * If a match is found, retrieve the explanation from the corresponding cell in the next column (e.g., column C).

   * Display the explanation in a message box using MessageBox.Show().

Example Code:

private void FindError()

{

    string error = textBox1.Text;

    using var workbook = new XLWorkbook("C:\\Users\\admin\\Desktop\\VSC-500.xlsx");

    var worksheet = workbook.Worksheet(1);


    int errorColumn = 2; // Assuming error codes are in column B (index 2)

    int explanationColumn = 3; // Explanation is in column C (index 3)


    for (int row = 1; row <= worksheet.RowsUsed(); row++)

    {

        if (worksheet.Cell(row, errorColumn).Value.ToString().Contains(error))

        {

            string explanation = worksheet.Cell(row, explanationColumn).Value.ToString();

            MessageBox.Show(explanation);

            return;

        }

    }

    MessageBox.Show("Error code not found!");

}

This code effectively searches the Excel table for the error code and displays the corresponding explanation in a user-friendly manner.


No comments:

Post a Comment