Кусок кода считывает файл Excel. Этот файл Excel содержит информацию, такую как номера рабочих мест клиентов, имена клиентов, сайты, описание работ и т. Д.Вставить гиперссылку в локальную папку в Excel с помощью Python
Что будет делать этот код при завершении (надеюсь), читается последняя строка рабочего листа (это взято из счетчик на листе в ячейке «P1»), создавать папки на основе содержимого ячеек и создавать гиперссылку на листе, чтобы открыть самую низкую локальную папку, которая была создана.
Я добыл информацию, мне нужно с листа, чтобы понять, что нужно создавать папкам, но я не в состоянии написать гиперссылка на ячейку в строке в столбце B.
#Insert Hyperlink to folder
def folder_hyperlink(last_row_position, destination):
cols = 'B'
rows = str(last_row_position)
position = cols + rows
final_position = "".join(position)
print final_position # This is just to check the value
# The statement below should insert hyperlink in eps.xlsm > worksheet jobnoeps at column B and last completed row.
ws.cell(final_position).hyperlink = destination
полный код ниже, но вот раздел, который предназначен для создания гиперссылки. Я также попробовал пакет «xlswriter» без радости. Искал интернет, и приведенный выше фрагмент является результатом того, что я нашел.
Кто-нибудь знает, что я делаю неправильно?
__author__ = 'Paul'
import os
import openpyxl
from openpyxl import load_workbook
import xlsxwriter
site_info_root = 'C:\\Users\\paul.EPSCONSTRUCTION\\PycharmProjects\\Excel_Jobs\\Site Information\\'
# This function returns the last row on eps.xlsm to be populated
def get_last_row(cell_ref = 'P1'): #P1 contains the count of the used rows
global wb
global ws
wb = load_workbook("eps.xlsm", data_only = True) #Workbook
ws = wb["jobnoeps"] #Worksheet
last_row = ws.cell(cell_ref).value #Value of P1 from that worksheet
return last_row
# This function will read the job number in format EPS-XXXX-YR
def read_last_row_jobno(last_row_position):
last_row_data = []
for cols in range(1, 5):
last_row_data += str(ws.cell(column = cols, row = last_row_position).value)
last_row_data_all = "".join(last_row_data)
return last_row_data_all
#This function will return the Customer
def read_last_row_cust(last_row_position):
cols = 5
customer_name = str(ws.cell(column = cols, row = last_row_position).value)
return customer_name
#This function will return the Site
def read_last_row_site(last_row_position):
cols = 6
site_name = str(ws.cell(column = cols, row = last_row_position).value)
return site_name
#This function will return the Job Discription
def read_last_row_disc(last_row_position):
cols = 7
site_disc = str(ws.cell(column = cols, row = last_row_position).value)
return site_disc
last_row = get_last_row()
job_no_details = read_last_row_jobno(last_row)
job_customer = read_last_row_cust(last_row)
job_site = read_last_row_site(last_row)
job_disc = read_last_row_disc(last_row)
cust_folder = job_customer
job_dir = job_no_details + "\\" + job_site + " - " + job_disc
#Insert Hyperlink to folder
def folder_hyperlink(last_row_position, destination):
cols = 'B'
rows = str(last_row_position)
position = cols + rows
final_position = "".join(position)
print final_position # This is just to check the value
# The statement below should insert hyperlink in eps.xlsm > worksheet jobnoeps at column B and last completed row.
ws.cell(final_position).hyperlink = destination
folder_location = site_info_root + job_customer + "\\" + job_dir
print folder_location # This is just to check the value
folder_hyperlink(last_row, folder_location)
Теперь моя функция гиперссылкой выглядит так после попытки xlsxwriter в соответствии с рекомендациями.
##Insert Hyperlink to folder
def folder_hyperlink(last_row_position, destination):
import xlsxwriter
cols = 'B'
rows = str(last_row_position)
position = cols + rows
final_position = "".join(position)
print final_position # This is just to check the value
workbook = xlsxwriter.Workbook('eps.xlsx')
worksheet = workbook.add_worksheet('jobnoeps')
print worksheet
worksheet.write_url(final_position, 'folder_location')
workbook.close()
Функция перезаписывает exsisting eps.xlsx, создает jobnoeps таблицу, а затем вставляет гиперссылку. Я играл со следующими строками, но не знаю, как заставить его открыть существующую xlsx и существующую вкладку jobnoeps, а затем ввести гиперссылку.
workbook = xlsxwriter.Workbook('eps.xlsx')
worksheet = workbook.add_worksheet('jobnoeps')
worksheet.write_url(final_position, 'folder_location')
Я обновил свой первый пост. Сделал некоторый прогресс в xlsxwriter. – Finchy70
XlsxWriter не может обновлять существующие файлы. Мне было непонятно, что вы обновляете существующий файл. Я бы рекомендовал openpyxl для этого, но я не думаю, что он поддерживает гиперссылки на папку. – jmcnamara