我需要 xlsx writer 来制作指向本地文件的相对路径超链接

I need xlsx writer to make relative path hyperlinks to local files

目标:在 xlsx 中拥有一个可以通过相对路径打开本地 pdf 文件的 hyperlink。

我可以使用该模块通过 os.getcwd()...不要用 write_url() 破坏 xlsx 中编码的 links。我不能 运行 目标目录中的代码(这会使这个问题消失),我必须 运行 在本地机器上生成包含所有 link 的 xlsx,然后将其移动到新目录,以便其他用户可以查看和使用 links(到将与 xlsx 一起移动的 pdf)。

未知:
文档的外部文件 url 部分中提到的“NETWORK”是如何工作的。它实际上是在谈论另一个 xlsx 文件,而不是不同类型的文件,所以它可能根本不起作用。 (文档 link:https://xlsxwriter.readthedocs.io/worksheet.html?highlight=write_url#worksheet-write-url

摘录:

Links to network files are also supported. Network files normally begin with two back slashes as >follows \NETWORK\etc. In order to generate this in a single or double quoted string you will >have to escape the backslashes, '\NETWORK\etc' or use a raw string r'\NETWORK\etc'. Alternatively, you can avoid most of these quoting problems by using forward slashes. These are >translated internally to backslashes:

worksheet.write_url('A14', "external:c:/temp/foo.xlsx")

worksheet.write_url('A15', 'external://NETWORK/share/foo.xlsx')

write_url(row, col, url[, cell_format[, string[, tip]]])

Write a hyperlink to a worksheet cell.

Parameters: row (int) – The cell row (zero indexed). col (int) – The cell column (zero indexed). url (string) – Hyperlink url. cell_format (Format) – Optional Format object. Defaults to the Excel hyperlink style. string (string) – An optional display string for the hyperlink. tip (string) – An optional tooltip.

解决方案:write_url().

中使用相对路径

所以 - excel 超链接可以是相对的也可以是绝对的。您可以提供它,它会自动处理裁决。如果是相对路径,那么excel会在点击超链接时找到自己的路径,然后修改给定的相对路径,或者直接使用给定的绝对路径。

例子

foo.xlsx 位于 C:\Desktop\folder\

bar.pdf 位于 C:\Desktop\folder\folder2\

设置write_url()中的超链接地址打开bar.pdf为:'folder2\bar.pdf'

当你点击foo.xlsx中的超链接时,excel会判断foo.xlsx的路径(不管在哪里,即使你在运行 构造超链接的代码),然后尝试查找提供的相对路径。

想象一下,在创建 foo.xlsx(及其使用 write_url() 的超链接)之后,您将文件夹 folder 的内容放在桌面上并删除文件夹 folder

现在, foo.xlsx 住在 C:\Desktop

bar.pdf 住在 C:\Destkop\folder2

然后打开 xlsx 并单击超链接。

Excel 将确定 xlsx 位于 C:\Desktop 并将尝试在 C:\Desktop\folder2\bar.pdf

处找到 bar.pdf