用python操作execl
时间: 2023-05-28 12:04:34 浏览: 70
使用Python操作Excel可以使用开源库openpyxl,下面给出一个简单的示例:
首先需要安装openpyxl库:
```
pip install openpyxl
```
然后就可以使用openpyxl库中的API来读写Excel文件了,例如读取Excel文件中的数据:
```python
import openpyxl
# 打开Excel文件,获取工作簿对象
workbook = openpyxl.load_workbook('example.xlsx')
# 获取工作表对象
sheet = workbook.active
# 读取单元格内容
cell_value = sheet.cell(row=1, column=1).value
print(cell_value)
# 遍历行
for row in sheet.rows:
for cell in row:
print(cell.value, end='\t')
print()
```
修改Excel文件中的数据:
```python
import openpyxl
# 打开Excel文件,获取工作簿对象
workbook = openpyxl.load_workbook('example.xlsx')
# 获取工作表对象
sheet = workbook.active
# 修改单元格内容
sheet.cell(row=1, column=1, value='new value')
# 保存修改后的Excel文件
workbook.save('example.xlsx')
```
以上示例仅为演示,openpyxl库还提供了更丰富的读写Excel文件的API,可以根据实际需求进行使用。
阅读全文
相关推荐












