简体   繁体   中英

Importing from Excel to MySQL Table Using Python 2.7

I'm trying to insert into a MySQL table from data in this Excel sheet: https://www.dropbox.com/s/w7m282386t08xk3/GA.xlsx?dl=0

The script should start from the second sheet "Daily Metrics" at row 16. The MySQL table already has the fields called date, campaign, users, and sessions.

Using Python 2.7, I've already created the MySQL connection and opened the sheet, but I'm not sure how to loop over those rows and insert into the database.

import MySQLdb as db
from openpyxl import load_workbook

wb = load_workbook('GA.xlsx')
sheetranges = wb['Daily Metrics']
print(sheetranges['A16'].value)

conn = db.connect('serverhost','username','password','database')

cursor = conn.cursor()

cursor.execute('insert into test_table ...')

conn.close()

Thank you for you help!

Try this and see if it does what you are looking for. You will need to update to the correct workbook name and location. Also, udate the range that you want to iterate over in for rw in wb["Daily Metrics"].iter_rows("A16:B20"):

from openpyxl import  load_workbook

wb = load_workbook("c:/testing.xlsx")

for rw in wb["Daily Metrics"].iter_rows("A16:B20"):
    for cl in rw:
        print cl.value

Only basic knowledge of MySQL and Openpyxl is needed, you can solve it by reading tutorials on your own.

Before executing the script, you need to create database and table. Assuming you've done it.

import openpyxl
import MySQLdb

wb = openpyxl.load_workbook('/path/to/GA.xlsx')
ws = wb['Daily Metrics']

# map is a convenient way to construct a list. you can get a 2x2 tuple by slicing 
# openpyxl.worksheet.worksheet.Worksheet instance and last row of worksheet 
# from openpyxl.worksheet.worksheet.Worksheet.max_row
data = map(lambda x: {'date': x[0].value, 
                      'campaign': x[1].value, 
                      'users': x[2].value, 
                      'sessions': x[3].value}, 
           ws[16: ws.max_row])

# filter is another builtin function. Filter blank cells out if needed
data = filter(lambda x: None not in x.values(), data)

db = MySQLdb.connect('host', 'user', 'password', 'database')
cursor = db.cursor()
for row in data:
    # execute raw MySQL syntax by using execute function
    cursor.execute('insert into table (date, campaign, users, sessions)'
                   'values ("{date}", "{campaign}", {users}, {sessions});'
                   .format(**row))  # construct MySQL syntax through format function
db.commit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM