超链接无法通过openpyxl工作

时间:2016-12-15 09:37:14

标签: python excel openpyxl

我在xlsx电子表格中使用以下代码段进行超链接。

  1. 从H2,H3,H4 ......
  2. 读取xlsx中的文件名
  3. 在当前文件夹(运行脚本的位置)中搜索文件
  4. 使用现有内容创建带搜索路径的超链接。
  5. 问题是。来自openpyxl的超链接,甚至没有用= HYPERLINK(“路径”,“真实文件名”)写作正在工作

    先谢谢。

    import os
    import openpyxl
    
    ColumnNum = 6
    RowNum = 2
    rootPath = ""
    
    def FindPathofFile(filename):
      for root, dirs, files in os.walk(rootPath):
          for file in files:
              if filename in file:
                   return(os.path.join(root, file))
    
    rootPath =input("Enter the Parent Path, Where the html files are present\n");
    SpreadSheetName = input("Enter the SwCTS spread sheet name, in which Hyperlinks to be created\n");
    wb = load_workbook(SpreadSheetName);
    ws = wb.get_sheet_by_name(input("Enter the SwCTS Tab Name, in which Hyperlinks to be created\n"));
    columnname = "H"+str(RowNum);
    valueofCell = ws[columnname].value;
    while True:
      if valueofCell:
        link = FindPathofFile(valueofCell);
        print ('=HYPERLINK("'+str(link)+'","'+str(valueofCell)+'")');
        #ws.cell(row=RowNum, column=ColumnNum).hyperlink = link;
        ws.cell(row=RowNum, column=ColumnNum).value ='=HYPERLINK("'+str(link)+'","'+str(valueofCell)+'")';
        RowNum = RowNum + 1;
        columnname = "H"+str(RowNum);
        valueofCell = ws[columnname].value;
      else:
        break;
    wb.save(SpreadSheetName);

2 个答案:

答案 0 :(得分:0)

嗯,我可以到达这里。虽然没有直接的方法来构建超链接,但在您的情况下我们可以这样做。事实上,我没有检查你的程序的彻底性。我相信你知道你还在做什么。我能够使用下面的代码构建指向现有文件的超链接。我看到我拥有的东西与你拥有的东西之间只有微小的逻辑差异。即缺少“风格”属性。

wb=openpyxl.Workbook()
s = wb.get_sheet_by_name('Sheet')
s['B4'].value = '=HYPERLINK("C:\\Users\\Manoj.Waghmare\\Desktop\\script.txt", "newfile")'
s['B4'].style = 'Hyperlink'
wb.save('trial.xlsx')

通过提及style属性为'Hyperlink'是关键。我拥有的所有其他代码对您来说可能并不重要。否则,style属性的值为'Normal' 奇怪的是,即使没有样式属性,我们工作的超链接,只是它缺乏风格!当然。虽然很奇怪,但我看到了一些陌生的东西。希望这会有所帮助。

答案 1 :(得分:0)

@Lucky,找不到任何创建超链接的失败。

以下所有Methodes都将工作超链接写入xlsx文件:

from openpyxl.workbook import Workbook
wb = Workbook()
ws = wb.worksheets[0]

link = 'http://www.example.org'
linkText = 'Click here'

Methode 1

ws.cell(row=2, column=6).hyperlink = link

显示' http://www.example.org '在单元格中,单击时打开超链接http://www.example.org

Methode 2

ws.cell(row=4, column=6).hyperlink = link
ws.cell(row=4, column=6).value = linkText

显示' 点击此处'在单元格中,单击时打开超链接http://www.example.org

Methode 3  (使用公式= HYPERLINK(link,cellText)

示例1:

ws.cell(row=6, column=6).value = '=HYPERLINK("http://www.example.org")'

显示' http://www.example.org '在单元格中,单击时打开超链接http://www.example.org

示例2:

ws.cell(row=8, column=6).value = '=HYPERLINK ( "http://www.example.org", "Click here" )'

显示' 点击此处'在单元格中,单击时打开超链接http://www.example.org

示例3:

ws.cell(row=10, column=6).value = '=HYPERLINK("http://www.", "Click ") & "example.org"'

显示' 点击example.org '在单元格中,单击时打开超链接http://www.example.org

使用Python测试:3.4.2 - openpyxl:2.4.1 - LibreOffice:4.3.3.2