簡體   English   中英

openpyxl讀出excel並保存到數據庫

[英]openpyxl read out excel and save into database

我正在嘗試讀出一個Excel工作表並將其保存到我的數據庫中。 這是我的excel表格: 在此處輸入圖片說明

我試圖獲取數據並將其保存到數據數組中的代碼如下所示(工作簿之前已通過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()

我只想說我知道該功能不起作用,但我認為它們表明了我想做的事情。 也許有人可以幫助我了解其工作原理。

感謝您的幫助!

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM