Mehmet Fatih

Mehmet Fatih

  • 855
  • 939
  • 41.3k

Displaying word data in a table

Dec 5 2023 3:39 PM

When converting Excel table to word, I get the following result. I cannot show the data in the table. I want help on this matter.

private void ExceltoWord_Load(object sender, EventArgs e)
{
    string excelFilePath = "C:\\Users\\Fatih\\Desktop\\Ögrenci Bilgileri.xlsx";
    string wordFilePath = "C:\\Users\\Fatih\\Desktop\\Ögrenci Bilgileri.docx";

    try
    {
        ConvertExcelToWord(excelFilePath, wordFilePath);
        Console.WriteLine("Conversion completed successfully.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"An error occurred during the conversion: {ex.Message}");
    }
}

static void ConvertExcelToWord(string excelFilePath, string wordFilePath)
{
    Word.Application wordApp = new Word.Application();
    Document wordDoc = wordApp.Documents.Add();

    // Open the Excel file
    Excel.Application excelApp = new Excel.Application();
    Workbook excelWorkbook = excelApp.Workbooks.Open(excelFilePath);
    Worksheet excelWorksheet = excelWorkbook.ActiveSheet;

    // Get the used range of the Excel worksheet
    Excel.Range usedRange = excelWorksheet.UsedRange;

    // Loop through each row in the used range
    for (int row = 1; row <= usedRange.Rows.Count; row++)
    {
        // Create a new paragraph in the Word document
        Paragraph paragraph = wordDoc.Content.Paragraphs.Add();

        // Loop through each column in the used range
        for (int col = 1; col <= usedRange.Columns.Count; col++)
        {
            // Get the value of the cell in the current row and column
            Excel.Range cell = usedRange.Cells[row, col];
            string cellValue = cell.Value != null ? cell.Value.ToString() : "";

            // Add the cell value to the paragraph
            paragraph.Range.Text += cellValue + " ";
        }
    }

    // Save and close the Word document
    wordDoc.SaveAs(wordFilePath);
    wordDoc.Close();

    // Close the Excel file
    excelWorkbook.Close();
    excelApp.Quit();
}

This is the result I got with the following code

This is exactly what I want to do.


Answers (2)