Example of python pandas Write to excel File

  • 2021-07-01 07:52:10
  • OfStack

It is very convenient for pandas to read and write csv data, but sometimes I hope to draw a simple chart through excel to see the data quality, change trend and save it. At this time, the data in csv format is slightly inconvenient, so I try to write the data directly into excel file.

pandas can be written to 1 or workbook. Two methods are described as follows:

1. If the entire DafaFrame is written to excel, you can do it by calling the to_excel () method. The sample code is as follows:


# output To save Dataframe
output.to_excel(' Save path  +  Filename .xlsx')

2. There are multiple data to be written into multiple excel workbooks. At this time, it is necessary to call the ExcelWriter () method to open an existing excel table as writer, then write the data to be saved into excel one by one through to_excel () method, and finally close writer.

The sample code is as follows:


#  Create 1 Empty excel Documents 
nan_excle = pd.DataFrame()
nan_excel.to_excel(path + filename)

#  Open excel
writer = pd.ExcelWriter(path + filename)
#sheets Is to be written excel List of Workbook Names 
for sheet in sheets:
    output.to_excel(writer, sheet_name=sheet)

#  Save writer Data in the excel
#  If you omit this statement, data will not be written to the excel In a file 
writer.save()

Note: When pandas reads and writes excel data, xlrd and xlwt libraries are needed when read_excel and to_excel read or write excel, and openpyxl library is needed when calling ExcelWriter method. I used conda to install these three libraries in anaconda prompt without success. Finally, I installed them through pip install command and used them normally.

Sample code:


pip install xlrd
pip install xlwt
pip install openpyxl

Related articles: