Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hyperlink not working through openpyxl

I was using the following code snippet for hyper linking in xlsx spread sheet.

  1. Reads the file name from xlsx from H2, H3, H4...
  2. Search for the file in the current folder (where script is running)
  3. Create hyper link with searched path with existing content.

Problem is .hyperlink from openpyxl and not even writing with =HYPERLINK("Path", "Real File Name") are working

Thanks in Advance.

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);
like image 202
Lucky Avatar asked Jul 04 '26 17:07

Lucky


1 Answers

Well, I could arrive at this. While there is no direct way to build a hyperlink, in your case we could do this way. As a matter of fact, I did not check the thoroughness of you program. I am sure you know what else you are doing. I was able to build a hyperlink to an existing file using the code below. I see that there is only a minor logical difference between what I have and what you have. i.e. the missing of "style" attribute.

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')

By mentioning the style attribute as 'Hyperlink' is the key. All other code I have may not be of any much importance to you. style attribute would otherwise have a value of 'Normal' Strange thing is even without the style attribute, the hyperlink we working but just that it was lacking style! of course. Though strange, I have seen stranger things. Hope this helps.

like image 112
Aditya Avatar answered Jul 07 '26 07:07

Aditya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!