Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pandas as pd
- import pythoncom
- import threading
- import time
- import xlwings as xw
- from concurrent.futures import ThreadPoolExecutor
- from rx import Observer
- from string import ascii_uppercase
- def create_curr_selection_df(curr_row_df, selection):
- if len(selection) == 3:
- column_ids = [selection[1]]
- else:
- column_ids = [x for x in (selection[1], selection[3])]
- curr_selection_df = curr_row_df.loc[:, column_ids]
- print(curr_row_df)
- print(selection)
- return curr_selection_df
- def monitor_loop(app: xw.App, observer: Observer, end_event: threading.Event):
- pythoncom.CoInitialize()
- workbook = xw.books.active
- sheet = workbook.sheets.active
- all_column_values = sheet.range(xw.Range('L2:Q2')).value
- column_to_header = {column_id: header for column_id, header in zip(ascii_uppercase[11:17], all_column_values)}
- while not end_event.is_set():
- # If you want to get current sheet name use: workbook.selection.sheet.name
- curr_selection = workbook.selection.address
- if workbook.selection.address != curr_selection:
- selection_address = workbook.selection.address.split('$')
- row_idx = selection_address[-1]
- cells_range_to_fetch = xw.Range(''.join(['L', row_idx, ':', 'Q', row_idx]))
- curr_data_frame = sheet.range(cells_range_to_fetch).options(pd.DataFrame, index=False, header=False).value
- curr_data_frame.columns = all_column_values
- if len(selection_address) == 3:
- curr_selection_columns = [column_to_header[selection_address[1]]]
- else:
- curr_selection_columns = \
- [column_to_header[letter] for letter in column_to_header.keys()
- if selection_address[1] <= letter <= selection_address[3]]
- # print('\n')
- # print(selection_address)
- # print(workbook.selection.address)
- # print(curr_selection)
- curr_selection_df = curr_data_frame.loc[:, curr_selection_columns]
- curr_selection = workbook.selection.address
- observer.on_next((curr_data_frame, all_column_values, row_idx, curr_selection_df))
- time.sleep(0.5)
- class CellObserver(Observer):
- def __init__(self, process_shared_resource):
- self.shared_res = process_shared_resource
- def on_next(self, excel_data):
- curr_row_df, all_columns, row_idx, curr_selection_df = excel_data
- self.shared_res.curr_row_df = curr_row_df
- self.shared_res.curr_selection_df = curr_selection_df
- self.shared_res.all_columns = all_columns
- self.shared_res.row_idx = row_idx
- def on_completed(self):
- print("done")
- def on_error(self, error):
- print('error')
- def launch_monitor_method(process_shared_resource):
- while not xw.apps:
- time.sleep(5)
- evt = threading.Event()
- tpe = ThreadPoolExecutor(1)
- f = tpe.submit(monitor_loop, xw.apps[0], CellObserver(process_shared_resource), evt)
- f.result()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement