如何使用python-docx将markdown格式超链接插入DOCX表格
实现方案
python-docx的表格单元格内容本质和正文段落结构一致,段落添加超链接的方法完全可以直接应用在表格场景中。实现逻辑分为两步:
- 编写辅助函数实现Markdown超链接解析,将混合了普通文本和超链接的字符串拆分为独立的内容片段
- 改写表格内容写入逻辑,将拆分后的内容依次写入单元格,超链接片段调用超链接插入方法生成可点击的链接
完整实现代码
import pandas as pd import docx from docx.shared import RGBColor from docx.oxml.ns import qn from docx.oxml import OxmlElement import re # 辅助函数:给指定段落添加超链接 def add_hyperlink(paragraph, text, url): part = paragraph.part r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True) hyperlink = OxmlElement('w:hyperlink') hyperlink.set(qn('r:id'), r_id, ) new_run = OxmlElement('w:r') rPr = OxmlElement('w:rPr') # 设置超链接样式:蓝色、下划线 c = OxmlElement('w:color') c.set(qn('w:val'), '0000FF') rPr.append(c) u = OxmlElement('w:u') u.set(qn('w:val'), 'single') rPr.append(u) new_run.append(rPr) new_run.text = text hyperlink.append(new_run) paragraph._p.append(hyperlink) return hyperlink # 辅助函数:解析Markdown格式超链接,拆分内容片段 def parse_md_text(text): md_link_pattern = re.compile(r'\[([^\]]+)\]\(([^)]+)\)') fragments = [] last_end = 0 for match in md_link_pattern.finditer(text): start, end = match.span() if start > last_end: fragments.append(('text', text[last_end:start])) link_text = match.group(1) link_url = match.group(2) # 自动补全http前缀,避免Word识别为内部路径 if not link_url.startswith(('http://', 'https://')): link_url = f'http://{link_url}' fragments.append(('link', link_text, link_url)) last_end = end if last_end < len(text): fragments.append(('text', text[last_end:])) return fragments # 示例数据 df = pd.DataFrame([["Some [string](www.google.com) is the link to google",'IDnum1',"China"], ["This is string 2","IDnum3","Australia"], ["some string3","IDNum5","America"]], columns = ["customer string","ID number","Country"]) doc = docx.Document() t = doc.add_table(df.shape[0]+1, df.shape[1]) # 写入表头 for j in range(df.shape[-1]): t.cell(0,j).text = df.columns[j] # 写入表体内容 for i in range(df.shape[0]): for j in range(df.shape[-1]): cell = t.cell(i+1,j) # 清空单元格默认生成的段落 cell.paragraphs[0].clear() current_paragraph = cell.paragraphs[0] content = str(df.values[i,j]) # 解析内容片段并写入 for frag in parse_md_text(content): if frag[0] == 'text': current_paragraph.add_run(frag[1]) elif frag[0] == 'link': add_hyperlink(current_paragraph, frag[1], frag[2]) doc.save('./test.docx')
注意事项
- 代码自动为不带http/https前缀的URL补全了http前缀,避免Word将链接识别为内部文档路径
- 超链接默认设置了蓝色+下划线的样式,可根据需要修改
add_hyperlink函数中的样式配置 - 同一个单元格内支持插入多个Markdown超链接,可正常识别混合排版的内容
内容的提问来源于stack exchange,提问作者Sushiix
相关产品推荐
相关产品推荐

