0

I am trying to develop a user form in python 2.7.3. Please note that I am a python beginner.

How to export user inputs (from python) to excel worksheet?

Thanks

0

1 Answer 1

2

For writing your form, you may want to use Tk - it's built into Python (import Tkinter).

For exporting to Excel, there are several options:

  1. write your data to a .csv file (import csv) then load it with Excel
  2. use a module to write to an .xls file
  3. use .COM automation to "remote-control" Excel

Edit: ok, here's a more specific answer using Tkinter and xlwt:

import Tkinter as tk
import xlwt
from xlwt.Utils import cell_to_rowcol2

class MyForm(tk.Frame):
    def __init__(self, master=None, cnf={}, **kw):
        tk.Frame.__init__(self, master, cnf, **kw)

        self.fname = tk.StringVar(value="myfile.xls")
        self.sheet = tk.StringVar(value="sheet1")
        self.cell  = tk.StringVar(value="x1")
        self.value = tk.StringVar(value="1234")

        tk.Label(master, text="File").grid(row=0, column=0, sticky=tk.E)
        tk.Entry(master, textvariable=self.fname).grid(row=0, column=1, padx=4, pady=4)

        tk.Label(master, text="Sheet").grid(row=1, column=0, sticky=tk.E)
        tk.Entry(master, textvariable=self.sheet).grid(row=1, column=1, padx=4, pady=4)

        tk.Label(master, text="Cell").grid(row=2, column=0, sticky=tk.E)
        tk.Entry(master, textvariable=self.cell).grid(row=2, column=1, padx=4, pady=4)

        tk.Label(master, text="Value").grid(row=3, column=0, sticky=tk.E)
        tk.Entry(master, textvariable=self.value).grid(row=3, column=1, padx=4, pady=4)

        go = tk.Button(master, text="Do it!", command=self.write_to_xls).grid(row=4, column=1, padx=4, pady=4, sticky=tk.W)
        self.grid()

    def write_to_xls(self):
        # create new workbook
        wb = xlwt.Workbook()

        # add sheet using given name
        ws = wb.add_sheet(self.sheet.get())

        # get offset of cell to write to
        row,col = cell_to_rowcol2(self.cell.get())

        # write text to cell
        ws.write(row, col, self.value.get())

        # save to given file name
        wb.save(self.fname.get())

def main():
    master = tk.Tk()
    myform = MyForm(master)
    tk.mainloop()

if __name__=="__main__":
    main()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.