Python Write Excel File
Syntax
import pandas as pd
# create a DataFrame
df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 32, 18, 47],
'Country': ['USA', 'Canada', 'UK', 'Australia']})
# write DataFrame to Excel file
df.to_excel('file_name.xlsx', index=False)
Example
import pandas as pd
data = {'Name':['Tom', 'Jim', 'George', 'Anne'],
'Age':[23, 17, 19, 21],
'Gender':['M', 'M', 'M', 'F']}
df = pd.DataFrame(data)
# write DataFrame to Excel file
df.to_excel('students.xlsx', sheet_name='Sheet1', index=False)
Output
This code will create a file named students.xlsx
in the current working directory with the following data:
Name | Age | Gender |
---|---|---|
Tom | 23 | M |
Jim | 17 | M |
George | 19 | M |
Anne | 21 | F |
Explanation
Using the pandas
library, you can create a DataFrame containing the data you want to write to an Excel file. Next, you can use the to_excel()
function to write the DataFrame to an Excel file. The first argument to the to_excel()
function is the file name you want to write to, and the index=False
parameter tells pandas
not to include the index in the output file.
The second example uses a dictionary to create a DataFrame for a list of students and then writes it to an Excel file named students.xlsx
with the sheet_name
parameter as Sheet1
and the index
parameter as False
.
Use
This code can be used to write data to an Excel file for archival or sharing purposes. It can be used for various data-related work, including data analysis, accounting, budgeting, and financial management.
Important Points
- The
pandas
library is required to execute the code. - The file extension should be
.xlsx
. - The
index
parameter is optional and defaults toTrue
. Set it toFalse
to exclude the index column. - If the file already exists, the
to_excel()
function will overwrite it by default. To avoid this, use themode
parameter to select a different write mode.
Summary
In this code snippet, we learned how to write data to an Excel file using the pandas
library. We also explored the various parameters and the importance of the pandas
library in the code. This knowledge is useful in various contexts, including data analysis, accounting, budgeting, and financial management.