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

2024-09-28 05:28:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在试着读出一个excel表格并将其保存到我的数据库中。这是我的excel表格: enter image description here

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

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)如下:

^{pr2}$

我只想说,我知道这个函数不起作用,但我认为它们表明了我想做什么。也许有人能帮我理解这是怎么回事。在

我很感谢你的帮助!在


Tags: 数据库datavaluecellcolumnexcel表格sheet
1条回答
网友
1楼 · 发布于 2024-09-28 05:28:39

IIUC,这里有一个使用^{}^{}的解决方案:

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

相关问题 更多 >

    热门问题