Python Xlsxwriter 简明教程

hyperlink 是一个字符串,单击时,它使用户转到其他位置,例如 URL、同一工作簿中的另一个工作表或计算机上的另一个工作簿。工作表类提供 write_url() 方法用于此目的。还可以在文本框中放置超链接,方法是使用 url 属性。

A hyperlink is a string, which when clicked, takes the user to some other location, such as a URL, another worksheet in the same workbook or another workbook on the computer. Worksheet class provides write_url() method for the purpose. Hyperlinks can also be placed inside a textbox with the use of url property.

首先,让我们了解一下 write_url() 方法。除了单元格位置外,它还需要定向到的 URL 字符串。

First, let us learn about write_url() method. In addition to the Cell location, it needs the URL string to be directed to.

import xlsxwriter

workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write_url('A1', 'https://www.tutorialspoint.com/index.htm')

workbook.close()

此方法有一些可选参数。一个是 Format 对象,用于配置要显示的 URL 的字体、颜色属性。我们还可以指定一个 URL 的工具提示字符串和一个显示文本。如果未给出文本,则 URL 本身将出现在单元格中。

This method has a few optional parameters. One is a Format object to configure the font, color properties of the URL to be displayed. We can also specify a tool tip string and a display text foe the URL. When the text is not given, the URL itself appears in the cell.

Example

支持的 URL 类型包括 http://https://ftp://mailto: 。在下面的示例中,我们使用这些 URL。

Different types of URLs supported are http://, https://, ftp:// and mailto:. In the example below, we use these URLs.

import xlsxwriter

workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()

worksheet.write_url('A1', 'https://www.tutorialspoint.com/index.htm')
worksheet.write_url('A3', 'http://localhost:8080')
worksheet.write_url('A5', 'ftp://www.python.org')
worksheet.write_url('A7', 'mailto:dummy@abc.com')

workbook.close()

Output

运行以上代码并使用 Excel 打开 hello.xlsx 文件。

Run the above code and open the hello.xlsx file using Excel.

hyperlink1

Example

我们还可以将超链接插入到同一工作簿中的另一个工作表或另一个工作簿中。这是通过在本地 URI 前加上 internal:external: 来完成的。

We can also insert hyperlink to either another workskeet in the same workbook, or another workbook. This is done by prefixing with internal: or external: the local URIs.

import xlsxwriter

workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()

worksheet.write_url('A1', 'internal:Sheet2!A1', string="Link to sheet2", tip="Click here")
worksheet.write_url('A4', "external:c:/test/testlink.xlsx", string="Link to other workbook")

workbook.close()

Output

请注意, stringtip 参数作为 linktool tip 的备用文本。上面程序的输出如下所示 −

Note that the string and tip parameters are given as an alternative text to the link and tool tip. The output of the above program is as given below −

hyperlink2