Python Program to Convert an HTML Table to Excel

Using the python program, you can convert an HTML table into an excel spreadsheet file. To do this task, some dependencies are needed. The dependencies modules are Python pandas, wheel, openpyxl.

Installing Dependencies

Install all the dependencies one after another to be configured automatically and properly.

Installing Wheel:

shell> pip install wheel

Installing Pandas:

shell> pip install pandas

Installing openpyxl:

shell> pip install openpyxl

Examples: Convert an HTML table to Exel file

After installing the dependencies, write the following python code called py-to-excel.py. Now try to run the following code.

#py-to-excel.py
import pandas as pd

url = "https://www.progracoding.com/data-types-in-c/"
table = pd.read_html(url)[0]
name ="dataname"
table.to_excel("%s.xlsx" % name)
print("Excel file has been created successfully!")

When the above code is executed. The file dataname.xlsx will be created in the current directory where the script file resides.

Example Explained

At the very first of the script, we have used Python Pandas library which is a data analysis library in Python. And notice that we have imported pandas as PD. It means, we called the python pandas command where PD stands for pandas command.

In the url variable, we put the URL where the HTML table resides. Then we have used the pandas read_html method to read the table data from the given link as a parameter. Name the new excel file that will be created. Then call the table.to_excel pandas method to create the excel file with the declared name.

Finally, we have printed that the file has been created.

Posted in