SoFunction
Updated on 2024-11-10

Example of python pandas writing to an excel file

pandas read, write csv data is very convenient, but sometimes want to draw a simple chart through excel to see the quality of the data, the trend and save, this time the csv format data is slightly inconvenient, so try to write the data directly to the excel file.

pandas can be written to a or workbook, the two methods are described below:

1, if the entire DafaFrame written to excel, then call to_excel () method can be achieved, the sample code is as follows:

# output is the Dataframe to be saved
output.to_excel('Save path + filename.xlsx')

2, there are multiple data need to write multiple excel workbook, then you need to call through the ExcelWriter () method to open an already existing excel form as a writer, and then through the to_excel () method will need to save the data written one by one into excel, and finally close the writer.

The sample code is as follows:

# Create an empty excel file
nan_excle = ()
nan_excel.to_excel(path + filename)

# Open excel
writer = (path + filename)
#sheets is a list of excel workbook names to write to
for sheet in sheets:
output.to_excel(writer, sheet_name=sheet)

# Save data from writer to excel
# If this statement is omitted, the data will not be written to the excel file created above
()

Note: pandas read, write excel data rely on read_excel, to_excel read or write excel need xlrd, xlwt library, call ExcelWriter method need openpyxl library. I used conda in anaconda prompt to install these three libraries without success, and finally installed them through the pip install command, and they work fine.

Sample code:

pip install xlrd
pip install xlwt
pip install openpyxl

This is the whole content of this article.