Search code examples
pythonexcelraw-input

Python- how do I write user input to an Excel file?


I'm new to Python so I hope this sounds right. How could I use Python to write to an Excel file from user input? I want my script to ask users "Name:" "Job Title:" "Building Number:" "Date:" etc. and from that raw input, fill in the corresponding columns one after the other in an Excel spreadsheet. I don't want future use of the script to overwrite previous data in the sheet either. I'd like each time to create a new line in the spreadsheet and then fill in the correct entries in each row. I hope that makes sense. Thank you so much in advance for your help.


Solution

  • You could use openpyxl to write to the workbook. Here's some basic usage, and should help avoid overwriting:

    import openpyxl
    wb = openpyxl.load_workbook('C:/test.xlsx')
    ws = wb.active
    i = 0
    cell_val = ''
    # Finds which row is blank first
    while cell_val != '':
        cell_val = ws['A' + i].value
        i += 1
    # Modify Sheet, Starting With Row i
    wb.save('C:/test.xlsx')
    

    Hope This Helps.

    Edited, getting input and time:

    For getting information from the user, use

    x = input('Prompt: ')
    

    However, if you want the actual current, I suggest using the time module:

    >>> from time import strftime
    >>> date = strftime('%m-%d-%y')
    >>> time = strftime('%I:%M%p')
    >>> print(date)
    08-28-15
    >>> print(time)
    01:57AM