131. Working with Excel Files

Working with Excel files in Python is a common task, and libraries like openpyxl and pandas can make it easy to manipulate Excel files (both .xls and .xlsx formats). Below are some examples using both libraries.

1. Using openpyxl to Create and Write Data to an Excel File

Copy

import openpyxl

# Create a new workbook and select the active sheet
workbook = openpyxl.Workbook()
sheet = workbook.active

# Writing data to cells
sheet['A1'] = 'Name'
sheet['B1'] = 'Age'
sheet['A2'] = 'Alice'
sheet['B2'] = 30
sheet['A3'] = 'Bob'
sheet['B3'] = 25

# Save the workbook to a file
workbook.save('people.xlsx')

print("Excel file created and data written.")

2. Reading Data from an Excel File with openpyxl

Copy


3. Using pandas to Read an Excel File

Copy


4. Using pandas to Write Data to an Excel File

Copy


5. Modifying Existing Excel Files with openpyxl

Copy


6. Appending Rows to an Existing Excel File with openpyxl

Copy


7. Working with Multiple Sheets in an Excel File using openpyxl

Copy


8. Reading Multiple Sheets with pandas

Copy


9. Applying Formatting to Excel Cells using openpyxl

Copy


10. Using pandas for Filtering and Writing Data to an Excel File

Copy


Key Points:

  • openpyxl: A powerful library to create, read, and modify Excel files (.xlsx). It allows cell-level manipulation and formatting.

  • pandas: Provides higher-level, fast manipulation of Excel data via DataFrame objects. It is useful for working with large datasets.

  • Writing/Reading Data: Both libraries offer easy-to-use functions to read from and write to Excel files.

  • Multiple Sheets: Both openpyxl and pandas support working with multiple sheets in a workbook.

Last updated