python办公自动化之excel
时间: 2023-08-09 20:10:24 浏览: 129
您好!对于Python办公自动化中的Excel,您可以使用`openpyxl`库来处理Excel文件。下面是一些常见的操作:
1. 安装`openpyxl`库:在命令行中运行`pip install openpyxl`。
2. 导入库:在Python脚本中使用`import openpyxl`来导入库。
3. 打开Excel文件:使用`openpyxl.load_workbook()`函数来打开一个Excel文件。
```python
from openpyxl import load_workbook
# 打开Excel文件
workbook = load_workbook('example.xlsx')
```
4. 选择工作表:使用`workbook.active`来选择默认的工作表,或者使用`workbook['Sheet1']`来选择特定的工作表。
```python
# 选择默认的工作表
worksheet = workbook.active
# 选择特定的工作表
worksheet = workbook['Sheet1']
```
5. 读取单元格数据:使用`worksheet.cell(row, column).value`来读取特定单元格的值。
```python
# 读取A1单元格的值
value = worksheet.cell(1, 1).value
```
6. 写入单元格数据:使用`worksheet.cell(row, column, value)`来写入特定单元格的值。
```python
# 写入B1单元格的值为'Hello'
worksheet.cell(1, 2, 'Hello')
```
7. 保存Excel文件:使用`workbook.save()`函数来保存修改后的Excel文件。
```python
# 保存修改后的Excel文件
workbook.save('example.xlsx')
```
这里只是介绍了一些基本的操作,`openpyxl`库还提供了更多的功能,比如合并单元格、设置样式等。***
阅读全文
相关推荐















