我正在尝试从 Python 输出 CSV 文件并将其中一个条目设为 Google 表格公式:
这就是公式 var 的样子:
strLink = "https://xxxxxxx.xxxxxx.com/Interact/Pages/Content/Document.aspx?id=" + strId + "&SearchId=0&utm_source=interact&utm_medium=general_search&utm_term=*"
strLinkCellFormula = "=HYPERLINK(\"" + strLink + "\", \"" + strTitle + "\")"
然后对于 CSV 的每一行,我都有这个:
strCSV = strCSV + strId + ", " + "\"" + strTitle + "\", " + strAuthor + ", " + strDate + ", " + strStatus + ", " + "\"" + strSection + "\", \"" + strLinkCellFormula +"\"\n"
这不太管用,Google 表格的超链接公式如下:
=HYPERLINK(url, title)
我似乎无法逃脱那个逗号。因此,在我的工作表中,我得到了一个带有标题的附加列,显然该公式不起作用。
尝试使用
;
作为公式参数分隔符。应该是一样的。
csv.writer
类来编写 CSV 行,而不是重新发明轮子。这会处理数据中的任何逗号和引号的转义,因此您无需构建自己的转义逻辑。这可以帮助您避免在 strLinkCellFormula = ...
和 strCSV = strCSV + ...
行中转义造成的混乱。
例如:
import csv
urls = ["https://google.com", "https://stackoverflow.com/", "https://www.python.org/"]
titles = ["Google", "Stack Overflow", "Python"]
with open("file.csv", "w") as fw:
writer = csv.writer(fw)
writer.writerow(["Company", "Website"])
for u, t in zip(urls, titles):
formula = f'=HYPERLINK("{u}", "Visit {t}")'
row = [t, formula]
writer.writerow(row)
请注意,在上面的
formula = ...
行中,我使用了f-string语法将URL和标题格式化为字符串。我还使用 撇号 来定义字符串,因为我知道该字符串将包含引号,并且我不想费心转义它们。
这将给出以下 CSV:
Company,Website
Google,"=HYPERLINK(""https://google.com"", ""Visit Google"")"
Stack Overflow,"=HYPERLINK(""https://stackoverflow.com/"", ""Visit Stack Overflow"")"
Python,"=HYPERLINK(""https://www.python.org/"", ""Visit Python"")"
已经处理了逗号和引号的转义。 Excel/GSheets 也可以正确读取它,因为它符合标准 CSV 格式:
对于您的具体情况,您可以像这样写入 CSV 文件:
with open(filename, "w") as wf:
writer = csv.writer(wf)
writer.writerow(headers) # if necessary
for ...:
strLink = f"https://xxxxxxx.xxxxxx.com/Interact/Pages/Content/Document.aspx?id={strID}&SearchId=0&utm_source=interact&utm_medium=general_search&utm_term=*"
strLinkCellFormula = f'=HYPERLINK("{strLink}", "{strTitle}")'
row = [strId, strTitle, strAuthor, strDate, strStatus, strSection, strLinkCellFormula]
writer.writerow(row)