You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Google Sheet带格式转为PDF并控制行渲染?

问题:将Google Sheet转换为保留完整格式(含合并单元格)的PDF

我正在尝试将Google Sheet转换为PDF文件,目前通过gspread库把表格转为HTML,再用pdfkit生成PDF。以下脚本可以运行,但会丢失合并单元格等所有格式信息:

import gspread
import pdfkit

wkhtmltopdf = r"wkhtmltopdf.exe"
config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf)

gc = gspread.service_account()
sh = gc.open("Test")
sheet = sh.sheet1.get_all_values()

table = ""
for row in sheet:
    table += "<tr>"
    for data in row:
        table += f"<td>{data}</td>"
    table += "</tr>"

html = f'''
<html>
    <body>
    <table>
        {table}
    </table>
    </body>
</html>
'''

pdfkit.from_string(html, "test.pdf", configuration=config)

生成的PDF丢失了所有格式,而gspread文档中没有提供获取合并单元格或格式数据的方法。

补充说明:
我知道可以用colspan标签实现单元格合并,但问题在于无法区分普通单元格和合并单元格,也没法确定合并范围;其他格式的获取也存在同样的问题。

为便于理解,变量sheet的返回值如下:

[['ID00001', '', '', '', ''],
['', '', '', '', ''],
['Merged', '', '', '', ''],
['1', 'A', '10', '11', '70'],
['2', 'B', '20', '22', '80'],
['3', 'C', '30', '33', '70'],
['4', 'D', '40', '44', '90'],
['5', 'E', '50', '55', '70'],
['6', 'F', '60', '66', '100']]

任何能解决该问题的方案均可,不局限于HTML方式,只需实现将Google Sheet转为带完整格式的PDF,并能控制行的渲染与否。

内容的提问来源于stack exchange,提问作者Anish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 06:20:14