Search directory for values inside xlsx, return workbook, sheet name, value and a hyperlink

Viewed 61

I have a code where I can search a folder directory for a value, it will then search all xlsx files inside the directory, and give me an output file with Workbook, sheet, row info, and hyperlink for its location.

I have managed to get most of them working but am having difficulties with the output file.

The Output file is giving me hyperlink like this Example "['/', '/', 'v', 'i', 'c', 't', 'o', 'r', '/'] in that one cell. I tried using replace function to remove ',' from that cell, so I have the correct string but what happens is that I just delete the whole-cell value instead.

df['Hyperlink']=df['Hyperlink'].str.replace(',','')

Can anyone guide me please, any improvements will be appriciated.

from argparse import _CountAction
from itertools import count
from sys import displayhook
import openpyxl
import pandas as pd
import os, glob
from openpyxl import Workbook, load_workbook
import tkinter
from tkinter import filedialog, Tk

tkinter.Tk().withdraw()

path = filedialog.askdirectory()
number = input("Search for value: ").casefold()

print('Searching...')
workbooks = [file for file in os.listdir(path) if file.endswith(".xlsx")]
workbooks = [_ for _ in workbooks if not _.startswith('~')]

sheetList3 = []


for workbook in workbooks:
    sheetList2 = []
    file_links = ['{}'.format(p) if len(p) < 256 else '' for p in path]
    ws = openpyxl.load_workbook(os.path.join(path, workbook))
    for sheet_name in (ws.get_sheet_names()):
        sheet = ws.get_sheet_by_name(sheet_name) 
        sheetList1 = [] 

        for value in sheet.values:
            if number in " ".join([str(_).lower() for _ in value if _]):
                tuple = (workbook, sheet_name, value, file_links)      
                sheetList1.append(tuple)
                sheetList2.append(tuple)
                sheetList3.append(tuple)

for count,value in enumerate(sheetList3):
    df=pd.DataFrame(sheetList3)
  
df=pd.DataFrame(sheetList3)
df.columns = ["Workbook", "Sheet", "Tag", "Hyperlink"]  

root = Tk()
try:
    with filedialog.asksaveasfile(mode='w', defaultextension=".xlsx") as file:
        df.to_excel(file.name , index = False)
except AttributeError:
    print("Save cancelled")
0 Answers
Related