openpyxl 合并相同单元格 并赋值
时间: 2023-10-13 09:22:57 浏览: 137
openpyxl官方文档
5星 · 资源好评率100%
使用 openpyxl 库,可以通过以下步骤合并相同单元格并赋值:
1. 导入 openpyxl 库和 Workbook 类:
```python
from openpyxl import Workbook
```
2. 加载 Excel 文件并选择要操作的工作表:
```python
workbook = openpyxl.load_workbook('example.xlsx')
worksheet = workbook.active
```
3. 定义一个字典(`merged_cells`)来存储要合并的单元格:
```python
merged_cells = {}
```
4. 遍历所有行并查找相同的值:
```python
for row in worksheet.iter_rows():
for cell in row:
value = cell.value
if value:
if value not in merged_cells:
merged_cells[value] = [cell.coordinate]
else:
merged_cells[value].append(cell.coordinate)
```
5. 对于相同的值,使用 merge_cells() 函数合并单元格,并在第一个单元格中写入该值:
```python
for value, coordinates in merged_cells.items():
if len(coordinates) > 1:
start, end = coordinates[0], coordinates[-1]
worksheet.merge_cells(start + ':' + end)
worksheet[start] = value
```
6. 保存 Excel 文件:
```python
workbook.save('example.xlsx')
```
完整代码示例:
```python
import openpyxl
workbook = openpyxl.load_workbook('example.xlsx')
worksheet = workbook.active
merged_cells = {}
for row in worksheet.iter_rows():
for cell in row:
value = cell.value
if value:
if value not in merged_cells:
merged_cells[value] = [cell.coordinate]
else:
merged_cells[value].append(cell.coordinate)
for value, coordinates in merged_cells.items():
if len(coordinates) > 1:
start, end = coordinates[0], coordinates[-1]
worksheet.merge_cells(start + ':' + end)
worksheet[start] = value
workbook.save('example.xlsx')
```
阅读全文