Openpyxl - ( Openpyxl Tutorial )
Heading h2
Syntax
import openpyxl
# Load the workbook
workbook = openpyxl.load_workbook('example.xlsx')
# Get the sheet names
sheet_names = workbook.sheetnames
# Get the active worksheet
worksheet = workbook.active
# Read a cell value
value = worksheet.cell(row=1, column=1).value
# Write a cell value
worksheet.cell(row=1, column=1, value='Hello, World!')
# Save the workbook
workbook.save('example.xlsx')
Example
import openpyxl
# Load the workbook
workbook = openpyxl.load_workbook('sales_data.xlsx')
# Get the sales data worksheet
worksheet = workbook['Sales Data']
# Print the total sales for each product category
categories = set([worksheet.cell(row=i, column=1).value for i in range(2, 30)])
for category in categories:
total_sales = sum([worksheet.cell(row=i, column=4).value for i in range(2, 30) if worksheet.cell(row=i, column=1).value == category])
print(f'Total sales for {category}: ${total_sales}')
# Save the workbook
workbook.save('sales_data.xlsx')
Output
The output will be the total sales for each product category in the sales data worksheet.
Explanation
Openpyxl is a Python library that allows you to read and write Excel documents using Python. It provides various functions and methods to manipulate Excel documents, including creating new workbooks, accessing worksheets, modifying cells, and saving workbooks.
In the above example, we load an existing sales_data.xlsx
workbook using the openpyxl.load_workbook()
method. We then get the Sales Data
worksheet using the workbook['worksheet_name']
syntax. We use the worksheet.cell()
method to read cell values and write new values to cells. Finally, we save the modified workbook using the workbook.save()
method.
Use
Openpyxl can be used for various tasks, such as data analysis, report generation, and data visualization. It provides a convenient way to read and write Excel documents, which can be useful for handling large amounts of data and automating repetitive tasks.
Important Points
- Openpyxl is a Python library for working with Excel documents
- It provides various methods and functions to read and write Excel files, including creating, modifying, and saving workbooks
- Openpyxl can be used for various tasks, such as data analysis, report generation, and data visualization
Summary
In conclusion, Openpyxl is a powerful Python library that can be used for working with Excel documents. It provides various functions and methods to manipulate Excel files, including creating, modifying, and saving workbooks. Openpyxl can be used for various tasks, such as data analysis, report generation, and data visualization. With its easy-to-use and intuitive API, Openpyxl is an excellent choice for handling Excel documents in your Python projects.