python openpyxl workbook用法
时间: 2023-09-25 21:15:45 浏览: 85
Python的openpyxl库是一个非常常用的Excel处理工具,它可以使你轻松地创建、读取和修改Excel文件。
下面是一些openpyxl workbook用法:
1. 创建一个新的workbook:
```
from openpyxl import Workbook
wb = Workbook()
```
2. 选择worksheet:
```
ws = wb.active
```
3. 设置worksheet的名称:
```
ws.title = "Sheet1"
```
4. 写入数据到worksheet:
```
ws['A1'] = 'Hello'
ws['B1'] = 'World'
```
5. 使用for循环在worksheet中写入多行数据:
```
rows = [
['Name', 'Age', 'Gender'],
['Bob', 25, 'Male'],
['Alice', 30, 'Female'],
['John', 35, 'Male']
]
for r in rows:
ws.append(r)
```
6. 保存workbook到文件:
```
wb.save('example.xlsx')
```
7. 从文件中读取数据:
```
from openpyxl import load_workbook
wb = load_workbook('example.xlsx')
ws = wb.active
for row in ws.iter_rows(values_only=True):
print(row)
```
8. 修改worksheet中的数据:
```
ws['A1'] = 'Hi'
for cell in ws['A']:
if cell.value == 'Bob':
cell.value = 'Bobby'
```
9. 删除worksheet中的行或列:
```
ws.delete_rows(4, 6) # 删除第4-6行
ws.delete_cols(2, 3) # 删除第2-3列
```
10. 复制worksheet:
```
new_ws = wb.copy_worksheet(ws)
new_ws.title = "Sheet2"
```
阅读全文