I’m working on a project where I need to log real-time data from a weigh scale into an Excel sheet. The catch is that the data should only be logged when I click a specific cell in the Excel sheet. How can I achieve this functionality using python or scala any other method? Any guidance or code snippets would be greatly appreciated!
First install the pyserial and openpyxl packages using pip:
pip install openpyxl pyserial
and then you can read the data and write data to an excel file using this Python script below. I tried to write it to a xlsx file. Port and baud rate may vary, change this accordingly please if you don't read any data:
import serial
import openpyxl
from openpyxl import load_workbook
import time
ser = serial.Serial('COM3', 9600, timeout=1)
excel_file = 'weigh_data.xlsx'
try:
workbook = load_workbook(filename=excel_file)
except FileNotFoundError:
workbook = openpyxl.Workbook()
workbook.save(excel_file)
sheet = workbook.active
def log_to_excel(weight):
next_row = sheet.max_row + 1
sheet[f'A{next_row}'] = weight
workbook.save(excel_file)
while True:
if ser.in_waiting > 0:
weight_data = ser.readline().decode('utf-8').rstrip()
log_to_excel(weight_data)
print(f"weight: {weight_data}")
time.sleep(1) # I also put sleep to read data every second
else:
print("no data available from the scale")
ser.close()