Python openpyxl: Excel File Handling
Here are some common ways to use the openpyxl library in Python for working with Excel files.
- Import the openpyxl library.
import openpyxl
- Open the Excel file.
workbook = openpyxl.load_workbook('filename.xlsx')
- Select the worksheet:
sheet = workbook.active # 选择活动工作表
sheet = workbook['Sheet1'] # 选择指定名称的工作表
- Get the value of the cell:
value = sheet['A1'].value # 读取A1单元格的值
- The value entered into the cell:
sheet['A1'] = 'Hello, World!' # 将字符串写入A1单元格
- Save the Excel file.
workbook.save('filename.xlsx')
These are just the basic usages of the openpyxl library, there are many other features such as reading entire worksheets, reading and writing multiple cells, creating new worksheets, etc. You can refer to the official documentation of openpyxl at https://openpyxl.readthedocs.io/ for more detailed usages and examples.