How to Import an Excel file chosen by user to mysql using python tkinter

Viewed 30

How to Import an Excel file(.xlsx) chosen by user to mysql database:
I am using python tkinter GUI
Note: the excel file will be selected by user

1 Answers

Unless you are unclear as to how to use TKinter's file dialogue, this doesn't look like a TKinter question. It seems to be just a Python question. That you're using TKinter doesn't seem to be relevant to the process of importing the file.

You said "import" so I'm assuming that you mean "import" and not "manipulate". It would be naïvely short-sighted to work directly with this proprietary format unless you were either manipulating the contents of the file or creating an .xlsx file from scratch.

What you should be doing is exporting the spreadsheet as a CSV file and importing that. In the past I've seen the argument that "this is an extra step", but ensuring that the file is saved in XML format (.xlsx), rather than one of the other many Excel file formats, is also an extra step -- so there really is no extra step. And even if you do consider it an extra step, users should be expected have a minimum level of competence to allow them to perform such a basic task as exporting a file to CSV.

I'm not going to spend a lot of time writing working code because there is simply not enough information to do so. I also haven't used MySQL for years. The last few years nearly all of my database stuff has been in SQLite, but this should all still apply. You would start by importing the MySQL module into your program and creating the table:

import mysql.connector as db
conn = db.connect(
    host=<uri>,
    user=<username>,
    password=<password>,
    database=<database_name>
    )
conn.execute("CREATE TABLE <tablename> (<column_definitions>);")

I think that's how I used to connect to my MySQL server. I'm assuming that you know the structure of the data in the Excel file and that it is not just some random spreadsheet with unknown data.

Next you would open your file and read and insert each row:

fh = open(<filename>, 'rt')
fh.readline()         #assuming there are headers: discard them
excelFile = fh.read() #read every line of file
for row in excelFile:
    sqlcmd = "INSERT INTO <tablename> (<column_names>) VALUES " + str(tuple(row.split(',')) + ";")
    db.execute(sqlcmd)

This is just an of-the-top-of-my-head example and will not work as written. For one thing, it only inserts strings; there is no data validation. SQLite is very forgiving of that and tends to correct inserted data on the fly, but my experience with MySQL is that it is more strictly typed.

That should get you started.

For a more complete answer it would be helpful to know the nature of the data: Is it for work? How often do you need to import this spreadsheet? Are the columns always the same? Are you creating a new table each time or are you inserting into an existing table?

Related