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
openpyxl to Create and Write Data to an Excel Fileimport 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
openpyxl3. Using pandas to Read an Excel File
pandas to Read an Excel File4. Using pandas to Write Data to an Excel File
pandas to Write Data to an Excel File5. Modifying Existing Excel Files with openpyxl
openpyxl6. Appending Rows to an Existing Excel File with openpyxl
openpyxl7. Working with Multiple Sheets in an Excel File using openpyxl
openpyxl8. Reading Multiple Sheets with pandas
pandas9. Applying Formatting to Excel Cells using openpyxl
openpyxl10. Using pandas for Filtering and Writing Data to an Excel File
pandas for Filtering and Writing Data to an Excel FileKey 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 viaDataFrameobjects. 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
openpyxlandpandassupport working with multiple sheets in a workbook.
Last updated