Importing from Excel to MySQL Table Using Python 2.7

ぐ巨炮叔叔 提交于 2021-02-08 04:32:16

问题


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!


回答1:


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()



回答2:


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


来源:https://stackoverflow.com/questions/43266126/importing-from-excel-to-mysql-table-using-python-2-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!