Python脚本从多个excel表读取并加载到azuresqldb表

2024-04-19 07:58:15 发布

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

我有一个包含多个电子表格的excel文件,我需要使用python脚本从这个excel文件中读取每个表格,并将数据加载到相应的azuresqldb表中。你知道吗

1个Excel文件6个工作表=6个Azure SQL DB表

请尽早对此要求提出意见。你知道吗

谢谢


Tags: 文件数据脚本dbsqlazureexcel表格
1条回答
网友
1楼 · 发布于 2024-04-19 07:58:15

例如,我创建了一个包含两张工作表的excel文件,如下图所示。你知道吗

enter image description here

有两种解决方案可以满足您将数据从excel表传输到sqlazure表的需要。你知道吗

  1. 通过^{}its document)读取echo sheet的数据生成insert sql,然后通过^{}^{}或其他方式执行这些insert sql。下面是我用Python从excel表读取数据的示例代码。你知道吗

    import xlrd
    
    book = xlrd.open_workbook("samples.xlsx")
    sheet_names = book.sheet_names()
    for sheet_name in sheet_names:
        sheet = book.sheet_by_name(sheet_name)
        recs = ",".join(["('{0[0]}', {0[1]})".format(sheet.row_values(i)) for i in range(sheet.nrows)])
        insert_sql = f"insert into {sheet_name} (name, age) values {recs};"
        print(insert_sql)
        # Connect to execute the insert data sql via pyodbc, pymssql or others
    

    以上代码的结果是。你知道吗

    insert into Table_A values ('Peason1', 18.0),('Peason2', 19.0),('Peason3', 20.0),('Peason4', 21.0),('Peason5', 22.0),('Peason6', 23.0),('Peason7', 24.0),('Peason8', 25.0),('Peason9', 26.0),('Peason10', 27.0);
    insert into Table_B values ('Peason11', 27.0),('Peason12', 26.0),('Peason13', 25.0),('Peason14', 24.0),('Peason15', 23.0),('Peason16', 22.0),('Peason17', 21.0),('Peason18', 20.0),('Peason19', 19.0),('Peason20', 18.0);
    

    同时,请参考Azure官方文档^{}^{},了解如何使用pyodbc或pymssql连接和查询Azure SQL数据库。

  2. 您可以通过pandas读取excel文件的表数据,然后通过SQLAlchemy连接通过函数^{}将数据写入sqlazure。下面是我的示例代码,用于读取excel文件的工作表数据以获取数据框。你知道吗

    import xlrd
    import pandas as pd
    
    file_name = "samples.xlsx"
    col_names = ["name", "age"]
    book = xlrd.open_workbook(file_name)
    sheet_names = book.sheet_names()
    for sheet_name in sheet_names:
        df = pd.read_excel(file_name, sheet_name=sheet_name, index_col=None, header=None, names=col_names)
        print(df)
        # Use df.to_sql with SQLAlchemy connection, that you can do it by yourself via refer to the pandas and SQLAlchemy documents.
    

    以上代码的结果是。你知道吗

           name  age
    0   Peason1   18
    1   Peason2   19
    2   Peason3   20
    3   Peason4   21
    4   Peason5   22
    5   Peason6   23
    6   Peason7   24
    7   Peason8   25
    8   Peason9   26
    9  Peason10   27
           name  age
    0  Peason11   27
    1  Peason12   26
    2  Peason13   25
    3  Peason14   24
    4  Peason15   23
    5  Peason16   22
    6  Peason17   21
    7  Peason18   20
    8  Peason19   19
    9  Peason20   18
    

    要通过SQLAlchemy连接sqlazure,请参阅SQLAlchemy文档^{}和其他SO线程Connecting to an Azure database using SQLAlchemy in Python

希望有帮助。你知道吗

相关问题 更多 >