04-11-2022, 03:31 PM
pd.to_excel() – An Unofficial Guide to Saving Data to Excel
Microsoft Excel is a cross-platform and battle-tested spreadsheet software widely used for data analysis and visualization. It is a powerful and user-friendly tool indeed! But how can we bring it to the next level?
We can combine Excel with Python to
Please continue reading and stay tuned for my Excel in Python series if it sounds great!
This tutorial is all about saving data to Excel.
Concretely, I will first introduce Excel’s data structure and lingos.
Then, you will learn the difference between four popular Python ways to save data to excel, including and .
Finally, I will focus on the method. I will guide you through four actual use cases in , ranging from one Excel worksheet, multiple Excel worksheets, multiple Excel workbooks, and dealing with index cases.
You can find all datasets and codes in this tutorial here. The data in our example datasets are not actual data and are only used for educational purposes.
Quick Introduction to Excel
Before jumping into reading data from Excel, let’s look at how data is stored in Excel and get ourselves familiar with some Excel lingos.
Simply put, data is stored in cells in Excel, and each cell can be identified with its unique row and column number pair.
Columns in Excel are labeled in alphabets, starting from ‘’, and rows in Excel are labeled in roman numbers, starting from ‘’. For example, in the following Excel picture, is the cell in the intersection of the first column and first row, ‘ID’.
![[Image: image-28.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-28.png)
Yes, you got the idea! It is just like the DataFrame data structure in our friends, pandas.
And if you want to select an area to dump data into Excel, you can imagine drawing a rectangle data region based on the upper-left cell of the part.
On top of that, other commonly seen Excel lingos include worksheets and workbooks.
Tip: More file extensions supported by Excel can be found in the Microsoft official doc here.
Now, you are ready to know how to read data from Excel!
Popular Python ways to Save Data to Excel
Here is the summary of popular Python ways to save data to excel:
![[Image: image-29-1024x495.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-29-1024x495.png)
One of’s advantages is engine compatibility. It uses multiple external engines for different Excel extensions, including , , and .
In summary, you can use and other libraries for specific Excel file formats and basic data processing. And please remember that and support newer Excel file formats.
However, I recommend using for data science and analytics applications because it supports most Excel file formats and accepts a DataFrame object with powerful methods.
Therefore, let’s see how to use to save data to Excel!
Saving Data to Excel – pandas.DataFrame.to_excel()
Since is the most powerful and inclusive way to save data from Excel files with different extensions, I will first introduce its syntax and walk you through three use cases with real Python codes below using .
Meet pandas.ExcelWriter
Before heading over to the method, we need to know a new friend, . It is a class for writing objects into excel sheets.
When you are trying to write to multiple sheets, you need to create an object and pass it to as the first parameter.
To create an object, we pass something to it according to its syntax:
![[Image: image-30-1024x260.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-30-1024x260.png)
Parameter |
Meta |
Description
|
required |
String or to an Excel file.
|
optional |
String specifying the engine to use for writing. Default is to use :
for for if is installed otherwise for
|
optional |
Format string for dates written into Excel files (e.g.).
|
optional |
Format string for objects written into Excel files. (e.g. ).
|
optional |
File mode to use ( for write; for append). The default is to use .
|
optional |
A dictionary that makes sense for a particular storage connection, e.g. host, port, username, password, etc.
|
optional |
What to do if a sheet exists under the append mode. Accepts. Default is .
: raise a .
: create a new sheet, with a name determined by the engine.
: delete the contents of the sheet before writing to it.
: write contents to the existing sheet without removing the old contents.
|
optional |
A dictionary containing keyword arguments passed into the engine.
Tip: Generally, you only need to use the four parameters in bold format. The default engine is automatically chosen depending on the file extension.
A small note: For compatibility with CSV writers, serializes lists and dicts to strings before writing.
Last, if you use the statement to create an , you do not need to worry about saving the change in the end! An example code to create an in the statement is:
![[Image: image-31-1024x417.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-31-1024x417.png)
After running the code, we create a new empty Excel file, with two new sheets, Class 5 and Class 6!
![[Image: image-32-888x1024.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-32-888x1024.png)
Meet pandas.DataFrame.to_excel
Hooray! Now, let’s look at the syntax and parameters of the method and get ourselves prepared for later examples!
Here is the syntax for:
![[Image: image-33-1024x312.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-33-1024x312.png)
To write a single object () to an Excel file, it is only necessary to specify a target file name. To write to multiple sheets, it is necessary to create an object with a target file name.
Parameter |
Meta |
Description
|
Required |
Target file name or object.
|
Optional |
Name of sheet containing DataFrame. Default is.
|
Optional |
Missing data representation.
|
Optional |
Format string for floating point numbers. For example will format 0.1234 to 0.12.
|
Optional |
Columns (in the DataFrame) to write.
|
Optional |
Row to be considered as the header, excluding from the data part., which means the first row. If , no header.
|
Optional |
Write row names (index). Default is, which means show index. If set to be , it means no index in the output Excel worksheet.
|
Optional |
Column label for the index.
|
Optional |
Upper left cell row to dump data frame. Default is 0.
|
Optional |
Upper left cell column to dump data frame. Default is 0.
|
Optional |
String specifying the engine to use for writing. Default is for .
for if is installed; otherwise .
|
Optional |
Write and Hierarchical Rows as merged cells.
|
Optional |
Encoding of the resulting excel file. Only necessary for, other writers support Unicode natively.
|
Optional |
Representation for infinity (there is no native representation for infinity in Excel).
|
Optional |
Display more information in the error logs.
|
Optional |
Specifies the one-based bottom-most row and right-most column that is to be frozen.
|
Optional |
Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc.
Tip: Generally, you only need to use the four parameters in bold format.
Please try to have an intuition for these parameters right now and I will cover the details for, , and parameters in our next exciting examples!
Getting started
To use the method, you need to first installthe package in your command line:
Tip: you might need to use instead of , depending on your environment.
Given the engine compatibility mentioned above, you also need to install respective engine libraries. For example, to use, you need to install this package on your command line:
Tip: you might need to use instead of , depending on your environment.
By the way, if you have already installed Anaconda, you can skip this step![[Image: 1f642.png]](https://s.w.org/images/core/emoji/13.1.0/72x72/1f642.png)
Dataset
In our examples, we will create Excel workbooks like the two Excel workbooks (), and , in our first Excel in Python series.
![[Image: image-34.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-34.png)
These workbooks have the same data structures and column names in each worksheet. For example, the following is the data in the worksheet in the workbook.
![[Image: image-35-1024x821.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-35-1024x821.png)
One row in each sheet represents a student in each class and the columns represent the student’s ID, Major, and Score respectively.
Concretely, has two worksheets, Class 1 and Class 2. And has two worksheets, Class 3 and Class 4.
You can find all datasets and codes in this tutorial here. The data in our example datasets are not actual data and are only used for educational purposes.
Save Data to One Worksheet
So, how can we save data to a single excel sheet? We can pass a target file name or create an object to do so!
For our example, we can create a new Excel file, and write some student data into the Class 5 sheet, specifying through the parameter .
![[Image: image-36-1024x444.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-36-1024x444.png)
After running the code, we can get the output Excel file:
![[Image: image-37-827x1024.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-37-827x1024.png)
Save Data to Multiple Worksheets
Likewise, we can save data to multiple worksheets by calling method multiple times.
For our example, we can create a new Excel file, and write some student data into the Class 5 sheet and Class 6 sheet, specifying through the parameter .
![[Image: image-38-1024x521.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-38-1024x521.png)
After running the code, we can get the output Excel file:
![[Image: image-39-736x1024.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-39-736x1024.png)
![[Image: image-40-760x1024.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-40-760x1024.png)
Save Data to Multiple Workbooks
To get multiple workbooks, we can just create multiple objects.
![[Image: 1f642.png]](https://s.w.org/images/core/emoji/13.1.0/72x72/1f642.png)
To give a quick example, let’s create two workbooks, and .
![[Image: image-41-1024x547.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-41-1024x547.png)
After running the code, we can get the output workbooks:
![[Image: image-42.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-42.png)
In the file, we can see that we have created two empty worksheets:
![[Image: image-43-602x1024.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-43-602x1024.png)
So far, we have understood the basic writing operations. Let’s move forward and deal with the most common issues—index and date![[Image: 1f642.png]](https://s.w.org/images/core/emoji/13.1.0/72x72/1f642.png)
Deal with Index
You can set up the index and index’ column label when calling the method.
Previously, our example codes set the index to be, which means no index column in the output Excel file. Let’s see what will happen if we set the index to be in the multiple worksheets scenario.
![[Image: image-44-1024x521.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-44-1024x521.png)
After running the code, we can see that we now have an index column, counting from zero.
![[Image: image-45-973x1024.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-45-973x1024.png)
On top of that, we can give a column name to the index column by specifying the parameter,.
![[Image: image-46-1024x573.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-46-1024x573.png)
After running the code, we can see that we now have an index column with a name, “No.”!
![[Image: image-47-1024x853.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-47-1024x853.png)
Conclusion
That’s how to save data to Excel. This is the second article in our Excel in Python series.
We learned about Excel’s data structure and commonly used lingos and four popular ways to save data to Excel in Python, including and .
Finally, we looked at four actual use cases in, ranging from one Excel worksheet, multiple Excel worksheets, multiple Excel workbooks, and dealing with index cases.
I hope you enjoy all this, and stay tuned for our following Excel in Python article on saving data to Excel! Happy coding!
Microsoft Excel is a cross-platform and battle-tested spreadsheet software widely used for data analysis and visualization. It is a powerful and user-friendly tool indeed! But how can we bring it to the next level?
We can combine Excel with Python to
- read data from Excel,
- save data to Excel with formats, formulas, and even charts, and
- automate Excel tasks in Python!
Please continue reading and stay tuned for my Excel in Python series if it sounds great!
This tutorial is all about saving data to Excel.
Concretely, I will first introduce Excel’s data structure and lingos.
Then, you will learn the difference between four popular Python ways to save data to excel, including
Code:
pandasCode:
openpyxlFinally, I will focus on the
Code:
pandas.DataFrame.to_excel()Code:
pandas.DataFrame.to_excel()You can find all datasets and codes in this tutorial here. The data in our example datasets are not actual data and are only used for educational purposes.
Quick Introduction to Excel
Before jumping into reading data from Excel, let’s look at how data is stored in Excel and get ourselves familiar with some Excel lingos.
Simply put, data is stored in cells in Excel, and each cell can be identified with its unique row and column number pair.
Columns in Excel are labeled in alphabets, starting from ‘
Code:
ACode:
1Code:
A1![[Image: image-28.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-28.png)
Yes, you got the idea! It is just like the DataFrame data structure in our friends, pandas.
And if you want to select an area to dump data into Excel, you can imagine drawing a rectangle data region based on the upper-left cell of the part.
On top of that, other commonly seen Excel lingos include worksheets and workbooks.
- A worksheet means a single spreadsheet in an Excel file.
- A workbook means a single Excel file with extensions like andCode:
.xlsx.Code:.xls
Tip: More file extensions supported by Excel can be found in the Microsoft official doc here.
Now, you are ready to know how to read data from Excel!
Popular Python ways to Save Data to Excel
Here is the summary of popular Python ways to save data to excel:
![[Image: image-29-1024x495.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-29-1024x495.png)
One of
Code:
pandas.DataFrame.to_excel()Code:
openpyxlCode:
xlwtCode:
xlsxwriter- “” supports old-style Microsoft Excel versions 95 to 2003 files (Code:
xlwt).Code:.xls
- “” supports newer Excel 2010 file formats (Code:
openpyxl).Code:.xlsx, .xlsm, .xltx, .xltm
- “” supports Excel 2007+ file format (Code:
xlsxwriter).Code:.xlsx
In summary, you can use
Code:
openpyxlCode:
openpyxlCode:
xlsxwriterHowever, I recommend using
Code:
pandas.DataFrame.to_excel()Therefore, let’s see how to use
Code:
pandas.DataFrame.to_excel()Saving Data to Excel – pandas.DataFrame.to_excel()
Since
Code:
pandas.DataFrame.to_excel()Code:
pandas.DataFrame.to_excel()Meet pandas.ExcelWriter
Before heading over to the
Code:
pandas.DataFrame.to_excelCode:
pandas.ExcelWriterCode:
pandas.DataFrameWhen you are trying to write to multiple sheets, you need to create an
Code:
ExcelWriterCode:
pandas.DataFrame.to_excel()To create an
Code:
ExcelWriterCode:
# Syntax for pandas.ExcelWriter
pandas.ExcelWriter(path[, engine=None[, date_format=None[, datetime_format=None[, mode='w'[, storage_options=None[, if_sheet_exists=None[, engine_kwargs=None[, **kwargs]]]]]])![[Image: image-30-1024x260.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-30-1024x260.png)
Parameter |
Meta |
Description
Code:
pathrequired |
String or
Code:
typing.BinaryIOCode:
engineoptional |
String specifying the engine to use for writing. Default is to use :
Code:
xlwtCode:
xls Code:
xlsxwriterCode:
xlsxCode:
xlsxwriterCode:
openpyxlCode:
odfCode:
odsCode:
date_formatoptional |
Format string for dates written into Excel files (e.g.
Code:
'YYYY-MM-DD'Code:
datetime_formatoptional |
Format string for
Code:
datetimeCode:
'YYYY-MM-DD HH:MM:SS'Code:
modeoptional |
File mode to use (
Code:
'w'Code:
'a'Code:
'w'Code:
storage_optionsoptional |
A dictionary that makes sense for a particular storage connection, e.g. host, port, username, password, etc.
Code:
if_sheet_existsoptional |
What to do if a sheet exists under the append mode. Accepts
Code:
{'error', 'new', 'replace', 'overlay'}Code:
'error'Code:
errorCode:
ValueErrorCode:
newCode:
replaceCode:
overlayCode:
engine_kwargsoptional |
A dictionary containing keyword arguments passed into the engine.
Tip: Generally, you only need to use the four parameters in bold format. The default engine is automatically chosen depending on the file extension.A small note: For compatibility with CSV writers,
Code:
ExcelWriterLast, if you use the
Code:
withCode:
ExcelWriterCode:
ExcelWriterCode:
withCode:
import pandas as pd df = pd.DataFrame()
excel_wb56_filepath = 'learn_excel_56.xlsx' # Syntax for create an ExcelWriter object in the with statement
# To create a new empty Excel file, learn_excel_56.xlsx with two new sheets!
with pd.ExcelWriter(excel_wb56_filepath) as writer: df.to_excel(writer, sheet_name='Class 5') df.to_excel(writer, sheet_name='Class 6')![[Image: image-31-1024x417.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-31-1024x417.png)
After running the code, we create a new empty Excel file,
Code:
learn_excel_56.xlsx![[Image: image-32-888x1024.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-32-888x1024.png)
Meet pandas.DataFrame.to_excel
Hooray! Now, let’s look at the syntax and parameters of the
Code:
pandas.DataFrame.to_excelHere is the syntax for
Code:
pandas.DataFrame.to_excelCode:
# Syntax for pandas.DataFrame.to_excel
DataFrame.to_excel(excel_writer[, sheet_name='Sheet1'[, na_rep=''[, float_format=None[, columns=None[, header=True[, index=True[, index_label=None[, startrow=0[, startcol=0[, engine=None[, merge_cells=True[, encoding=None[, inf_rep='inf'[, verbose=True[, freeze_panes=None[, storage_options=None]]]]]]]]]]]]]]]])![[Image: image-33-1024x312.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-33-1024x312.png)
To write a single object (
Code:
pandas.DataFrameCode:
.xlsxCode:
ExcelWriterParameter |
Meta |
Description
Code:
excel_writerRequired |
Target file name or
Code:
ExcelWriterCode:
sheet_nameOptional |
Name of sheet containing DataFrame. Default is
Code:
"Sheet 1"Code:
na_repOptional |
Missing data representation.
Code:
Default = ""Code:
float_formatOptional |
Format string for floating point numbers. For example
Code:
float_format="%.2f"Code:
columnOptional |
Columns (in the DataFrame) to write.
Code:
headerOptional |
Row to be considered as the header, excluding from the data part.
Code:
Default = TrueCode:
NoneCode:
indexOptional |
Write row names (index). Default is
Code:
TrueCode:
FalseCode:
index_labelOptional |
Column label for the index.
Code:
startrowOptional |
Upper left cell row to dump data frame. Default is 0.
Code:
startcolOptional |
Upper left cell column to dump data frame. Default is 0.
Code:
engineOptional |
String specifying the engine to use for writing. Default is
Code:
xlwtCode:
xlsCode:
xlsxwriterCode:
xlsxCode:
xlsxwriterCode:
openpyxlCode:
merge_cellsOptional |
Write
Code:
MultiIndexCode:
encodingOptional |
Encoding of the resulting excel file. Only necessary for
Code:
xlwtCode:
inf_repOptional |
Representation for infinity (there is no native representation for infinity in Excel).
Code:
verboseOptional |
Display more information in the error logs.
Code:
freeze_panesOptional |
Specifies the one-based bottom-most row and right-most column that is to be frozen.
Code:
storage_optionsOptional |
Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc.
Tip: Generally, you only need to use the four parameters in bold format.
Please try to have an intuition for these parameters right now and I will cover the details for
Code:
sheet_nameCode:
indexCode:
index_labelGetting started
To use the
Code:
pandas.DataFrame.to_excelCode:
pandasCode:
$ pip install pandasTip: you might need to use
Code:
pip3Code:
pipGiven the engine compatibility mentioned above, you also need to install respective engine libraries. For example, to use
Code:
openpyxlCode:
$ pip install openpyxlTip: you might need to use
Code:
pip3Code:
pipBy the way, if you have already installed Anaconda, you can skip this step
![[Image: 1f642.png]](https://s.w.org/images/core/emoji/13.1.0/72x72/1f642.png)
Dataset
In our examples, we will create Excel workbooks like the two Excel workbooks (
Code:
.xlsxCode:
learn_excel_12Code:
learn_excel_34![[Image: image-34.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-34.png)
These workbooks have the same data structures and column names in each worksheet. For example, the following is the data in the
Code:
Class_1Code:
learn_excel_12![[Image: image-35-1024x821.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-35-1024x821.png)
One row in each sheet represents a student in each class and the columns represent the student’s ID, Major, and Score respectively.
Concretely,
Code:
learn_excel_12Code:
learn_excel_34You can find all datasets and codes in this tutorial here. The data in our example datasets are not actual data and are only used for educational purposes.
Save Data to One Worksheet
So, how can we save data to a single excel sheet? We can pass a target file name or create an
Code:
ExcelWriterFor our example, we can create a new Excel file,
Code:
learn_excel_56Code:
sheet_nameCode:
import pandas as pd # For our writing mode example,
# we can create a new Excel file, learn_excel_56
# and write some student data into it.
excel_fp = 'learn_excel_56.xlsx'
class5_df = pd.DataFrame( {'ID': [51, 52], 'Major': ['English', 'Math'], 'Score': [98, 89]}) with pd.ExcelWriter(excel_fp, mode='w') as writer: class5_df.to_excel(writer, sheet_name='Class 5', index=False)![[Image: image-36-1024x444.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-36-1024x444.png)
After running the code, we can get the output Excel file:
![[Image: image-37-827x1024.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-37-827x1024.png)
Save Data to Multiple Worksheets
Likewise, we can save data to multiple worksheets by calling
Code:
pandas.DataFrame.to_excel()For our example, we can create a new Excel file,
Code:
learn_excel_56Code:
sheet_nameCode:
import pandas as pd # For our writing mode example,
# we can create a new Excel file, learn_excel_56
# and write some student data into it.
excel_fp = 'learn_excel_56.xlsx'
class5_df = pd.DataFrame( {'ID': [51, 52], 'Major': ['English', 'Math'], 'Score': [98, 89]})
class6_df = pd.DataFrame( {'ID': [61, 62], 'Major': ['History', 'Math'], 'Score': [78, 96]}) with pd.ExcelWriter(excel_fp, mode='w') as writer: class5_df.to_excel(writer, sheet_name='Class 5', index=False) class6_df.to_excel(writer, sheet_name='Class 6', index=False)![[Image: image-38-1024x521.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-38-1024x521.png)
After running the code, we can get the output Excel file:
![[Image: image-39-736x1024.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-39-736x1024.png)
![[Image: image-40-760x1024.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-40-760x1024.png)
Save Data to Multiple Workbooks
To get multiple workbooks, we can just create multiple
Code:
pandas.ExcelWriter![[Image: 1f642.png]](https://s.w.org/images/core/emoji/13.1.0/72x72/1f642.png)
To give a quick example, let’s create two workbooks,
Code:
learn_excel_78Code:
learn_excel_910Code:
import pandas as pd # let’s create two workbooks, learn_excel_78 and learn_excel_910.
wb78_fp = 'learn_excel_78.xlsx'
wb910_fp = 'learn_excel_910.xlsx' df = pd.DataFrame() with pd.ExcelWriter(wb78_fp, mode='w') as writer_78, pd.ExcelWriter(wb910_fp, mode='w') as writer_910: df.to_excel(writer_78, sheet_name='Class 7', index=False) df.to_excel(writer_78, sheet_name='Class 8', index=False) df.to_excel(writer_910, sheet_name='Class 9', index=False) df.to_excel(writer_910, sheet_name='Class 10', index=False)![[Image: image-41-1024x547.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-41-1024x547.png)
After running the code, we can get the output workbooks:
![[Image: image-42.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-42.png)
In the
Code:
learn_excel_78![[Image: image-43-602x1024.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-43-602x1024.png)
So far, we have understood the basic writing operations. Let’s move forward and deal with the most common issues—index and date
![[Image: 1f642.png]](https://s.w.org/images/core/emoji/13.1.0/72x72/1f642.png)
Deal with Index
You can set up the index and index’ column label when calling the
Code:
pandas.DataFrame.to_excel()Previously, our example codes set the index to be
Code:
FalseCode:
TrueCode:
import pandas as pd # For our writing mode example,
# we can create a new Excel file, learn_excel_56
# and write some student data into it.
excel_fp = 'learn_excel_56.xlsx'
class5_df = pd.DataFrame( {'ID': [51, 52], 'Major': ['English', 'Math'], 'Score': [98, 89]})
class6_df = pd.DataFrame( {'ID': [61, 62], 'Major': ['History', 'Math'], 'Score': [78, 96]}) with pd.ExcelWriter(excel_fp, mode='w') as writer: class5_df.to_excel(writer, sheet_name='Class 5', index=True) class6_df.to_excel(writer, sheet_name='Class 6', index=True)![[Image: image-44-1024x521.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-44-1024x521.png)
After running the code, we can see that we now have an index column, counting from zero.
![[Image: image-45-973x1024.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-45-973x1024.png)
On top of that, we can give a column name to the index column by specifying the parameter,
Code:
index_labelCode:
import pandas as pd # For our writing mode example,
# we can create a new Excel file, learn_excel_56
# and write some student data into it.
excel_fp = 'learn_excel_56.xlsx'
class5_df = pd.DataFrame( {'ID': [51, 52], 'Major': ['English', 'Math'], 'Score': [98, 89]})
class6_df = pd.DataFrame( {'ID': [61, 62], 'Major': ['History', 'Math'], 'Score': [78, 96]}) with pd.ExcelWriter(excel_fp, mode='w') as writer: class5_df.to_excel(writer, sheet_name='Class 5', index=True, index_label='No.') class6_df.to_excel(writer, sheet_name='Class 6', index=True, index_label='No.')![[Image: image-46-1024x573.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-46-1024x573.png)
After running the code, we can see that we now have an index column with a name, “No.”!
![[Image: image-47-1024x853.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-47-1024x853.png)
Conclusion
That’s how to save data to Excel. This is the second article in our Excel in Python series.
We learned about Excel’s data structure and commonly used lingos and four popular ways to save data to Excel in Python, including
Code:
pandasCode:
openpyxlFinally, we looked at four actual use cases in
Code:
pandas.DataFrame.to_excelI hope you enjoy all this, and stay tuned for our following Excel in Python article on saving data to Excel! Happy coding!

