openpyxl读出excel并保存到数据库中

时间:2017-11-22 11:00:04

标签: python django database excel openpyxl

我正在尝试读取excel表并将其保存到我的数据库中。这是我的excel表: enter image description here

我试图获取数据并将其保存到数据数组中的代码如下所示(使用load_workbook之前加载了工作簿):

def getExampleData(workbook):
    sheet = workbook.get_sheet_by_name('ExampleData')
    titleCell = sheet.cell('D1')
    assert titleCell.value = u'Overview'
    startRow = (2, 1)
    endRow = (6, 1) #this is the first empty row and I have it hardcodened 
                     to this time but it needs to be dynamically found 
                     in the future
    data['ExData'] = {}
    for i in range(startRow, endRow):
        exData = {}
        exData['Name'] = sheet.cell(row=I, column=1).value
        exData['Param1'] = sheet.cell(row=I, column=2).value
        exData['Param2'] = sheet.cell(row=I, column=3).value
        exData['Param3'] = sheet.cell(row=I, column=4).value
        data['ExData'| = exData
return data['ExData']

然后我希望它将它加载到名为ExampleDB的数据库表中(整个项目是使用Django制作的,所以我只使用导入加载ExampleDB),如下所示:

def saveExampleData():
xData = data['ExData']
ex = ExampleDB.objects.filter(name = xData['Name'], param1 = xData['Param1'],
               param2 = xData['Param2'], param3 = xData['Param3])
ex.save()

我只是想说,我知道这些功能不起作用,但我认为它们显示了我想做的事情。也许有人可以帮助我理解它是如何工作的。

我感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

IIUC,这是一个解决方案,使用pandassqlalchemy

from sqlalchemy import create_engine
import pandas as pd

db = create_engine('sqlite:///stocks.db')
df = pd.read_excel('excelfile.xlsx')
df.to_sql('required_table', db, if_exists='append')