python excel 写入超链接
时间: 2023-11-15 12:57:22 浏览: 539
可以使用 openpyxl 库来实现在 Excel 中写入超链接。具体实现步骤如下:
1. 导入 openpyxl 库:
```python
import openpyxl
```
2. 打开 Excel 文件并选择工作表:
```python
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.active
```
3. 创建超链接对象并设置链接地址和显示文本:
```python
from openpyxl.utils import quote_sheetname
link = openpyxl.worksheet.hyperlink.Hyperlink(ref=f"A1", target="https://www.example.com")
link.display = "Example Website"
```
其中,`ref` 参数表示超链接所在单元格的位置,`target` 参数表示链接地址,`display` 参数表示链接的显示文本。
4. 将超链接对象添加到指定单元格:
```python
sheet.cell(row=1, column=1).hyperlink = link
```
其中,`row` 和 `column` 参数表示单元格的行号和列号。
5. 保存 Excel 文件:
```python
wb.save('example.xlsx')
```
完整代码示例:
```python
import openpyxl
from openpyxl.utils import quote_sheetname
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.active
link = openpyxl.worksheet.hyperlink.Hyperlink(ref=f"A1", target="https://www.example.com")
link.display = "Example Website"
sheet.cell(row=1, column=1).hyperlink = link
wb.save('example.xlsx')
```
阅读全文
相关推荐
















