Hello, I am Xiao Wu 🧐

The to. XXX series of functions will be used to export data to Pandas.

The more common ones are pd.to_csv() and pd.to_excel(). But you can also convert it to Html, using the function pd.to_html()!

b

Reading Excel

Today we want to achieve Excel to HTML format, first need to read Excel table data.

import pandas as pd
data = pd.read_excel('test. XLSX')
Copy the code

View the data

data.head()
Copy the code

Let’s learn how to convert a DataFrame into an HTML table.

Generate Html

The to_html() function converts the DataFrame directly into an HTML table with one line of code:

html_table = data.to_html('test. HTML')
Copy the code

After running the code above, you have a test.html file in your working directory. Open it with a Web browser and it will display the following content: 👇

print(data.to_html())
Copy the code

Print to see that the internal structure of the DataFrame is automatically converted to ,, tags embedded in the table, preserving all the internal hierarchy.

Adjust the format

You can also customize the modification parameters to adjust the format of the generated HTML.

html_table = data.to_html('test. HTML',header = True,index = False,justify='center')
Copy the code

Open the newly generated test.html file again and find that the format has changed.

If you want to make further changes to the format (adding titles, changing colors, and so on), you’ll need some HTML knowledge to adjust the text in the generated test.html files.

For those of you who need to display pages, you’ll need to use the Flask library.

summary

Pandas provides the read_html() and to_html() functions for reading and writing HTML files. These two functions are very useful. One easily converts complex data structures such as dataframes into HTML tables. Another without complex crawler, a few lines of simple code can grab Table Table data, it is a magic tool!

The to_html() function is used in Pandas. The biggest advantage of using this function is that you can generate tabular HTML without any knowledge of HTML.

end

If you are interested in the other function (how Pandas crawls), please click 👍 in the bottom right corner of this article.