Home > database >  Export HTML table to Excel file using C# (WinForms .NET 5)
Export HTML table to Excel file using C# (WinForms .NET 5)

Time:11-04

I need to convert a HTML table with styling to an .XLSX file.

I managed to do that using the free version of GemBox.Spreadsheet, for now I don't mind the limitation of the free version but the problem is that numbers are considered as text when I open the Excel file. Is there any solution to that without manually opening the Excel file and converting them myself ? Or even a free alternative to GemBox library ?

File.WriteAllText("Table.html", html);
ExcelFile.Load("Table.html", LoadOptions.HtmlDefault).Save("Test.xlsx");

My HTML looks like this

<html>
  <body>
    <center>
      <table border="1" cellpadding="0" cellspacing="0">
        <tr>
          <td>Crimson Witch</td>
          <td>HP</td>
          <td>ATK</td>
          <td>DEF</td>
        </tr>
        <tr>
          <td>Flower</td>
          <td>10</td>
          <td style="background-color: #808080"></td>
          <td style="background-color: #808080"></td>
        </tr>
        <tr>
          <td>Plume</td>
          <td style="background-color: #808080"></td>
          <td>10</td>
          <td style="background-color: #808080"></td>
        </tr>
      </table>
    </center>
  </body>
</html>

Solution :

File.WriteAllText("Table.html", html.Replace("<center>", string.Empty).Replace("</center>", string.Empty));
ExcelFile.Load("Table.html", LoadOptions.HtmlDefault).Save("Test.xlsx");

CodePudding user response:

The problem occurs because the <table> is inside the <center>.

Try removing the <center> element.

  • Related