Skip to main content

How to write to an Excel file in Python

How to write to an Excel file in Python.

Here's a step-by-step tutorial on how to write to an Excel file using Python:

Step 1: Install Necessary Packages

First, you need to install the openpyxl package, which allows you to work with Excel files in Python. You can install it using pip by running the following command in your terminal or command prompt:

pip install openpyxl

Step 2: Import the Required Modules

Next, you need to import the necessary modules in your Python script. You will need the openpyxl module to work with Excel files:

import openpyxl

Step 3: Create a Workbook Object

To write to an Excel file, you first need to create a workbook object. This object represents the Excel file and contains all the data and formatting information. You can create a new workbook object by calling the Workbook() function:

workbook = openpyxl.Workbook()

Step 4: Access the Active Sheet

By default, a new workbook contains one sheet called "Sheet". To write data to this sheet, you need to access it. You can do this by using the active attribute of the workbook object:

sheet = workbook.active

Step 5: Write Data to Cells

Now that you have access to the worksheet, you can start writing data to specific cells. You can do this by using the cell() method of the sheet object and providing the row and column indices:

sheet.cell(row=1, column=1, value="Hello")
sheet.cell(row=1, column=2, value="World!")

Step 6: Save the Workbook

Once you have finished writing data to the Excel file, you need to save it. You can save the workbook object by calling the save() method and providing the desired file name:

workbook.save(filename="example.xlsx")

Step 7: Close the Workbook

After saving the Excel file, it's good practice to close the workbook. You can do this by calling the close() method of the workbook object:

workbook.close()

That's it! You have successfully written data to an Excel file using Python. Now you can open the generated file "example.xlsx" and see the written data.

Here's a complete example that puts all the steps together:

import openpyxl

# Create a new workbook
workbook = openpyxl.Workbook()

# Access the active sheet
sheet = workbook.active

# Write data to cells
sheet.cell(row=1, column=1, value="Hello")
sheet.cell(row=1, column=2, value="World!")

# Save the workbook
workbook.save(filename="example.xlsx")

# Close the workbook
workbook.close()

Feel free to modify the example to suit your specific needs. Happy coding!