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
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
3. Using pandas to Read an Excel File
4. Using pandas to Write Data to an Excel File
5. Modifying Existing Excel Files with openpyxl
6. Appending Rows to an Existing Excel File with openpyxl
7. Working with Multiple Sheets in an Excel File using openpyxl
8. Reading Multiple Sheets with pandas
9. Applying Formatting to Excel Cells using openpyxl
10. Using pandas for Filtering and Writing Data to an Excel File
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 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