【问题标题】:slicing column name from every head row in excel sheet and looping though sheet name's in pandas从 excel 表中的每个头行切片列名并循环遍历 pandas 中的表名
【发布时间】:2020-11-11 02:41:36
【问题描述】:

我正在尝试从包含多个工作表的 Excel 文件中插入数据,每个工作表名称都存在于数据库中的相应表中。现在我认为的一种方法是在工作表名称上循环并在循环中创建一个递归 SQL,该循环适用于所有工作表名称。现在在循环中假设第一个工作表名称出现然后几乎没有检查数据库中是否存在表并验证工作表中的列名以及数据库中的列名。如果一切正常,它会将工作表数据插入数据库。

我面临的挑战是:

1 - 从 pandas 获取 Sheetname

        xls = pd.ExcelFile<filepath>
        Sheet_name = x.sheet_names

I am not able to loop through it although it contains all the sheet name but for() is not working.
Help me with a iteration code.

2 - 帮我从每张纸的头行切出列名以确认列名。

I am placing a few piece of code that i have been working on, help me with syntax error's as well

Their are errors in SQL code as well Please help me with them also

代码:

import pandas as pd
Import the oracle lib

Create -----> DB_Connection 
mycursor = DB_Connection.cursor()
xls = pd.ExcelFile('File Path')
SheetNames = xls.sheet_names

for i in SheetNames:
    SelectSql = "SELECT TABLE_NAME FROM all_tab_columns where OWNER = 'XYZZZ' and TABLE_NAME = '"i"' "
    mycursor.execute(SelectSql)
    QueryResult = mycursor.fethcone()

if(pd.isnull(QueryResult)):
    Print("Table doesn't exist in database")
else:
    """    Add the Data frame slicing code to get Column name's to Check if same Exist in Database or Not    """
    
    GetColumnSql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '"i"' ORDER BY ORDINAL_POSITION"
    mycursor.execute(GetColumnSql)
    ColumnName = mycursor.fetchall()
    
    InsertSql = "INSERT INTO '"i"'('"ColumnName"') VALUES(%s,%s,%s,%s,%s)"
    VAL0 = """  insert from dataframe  """
    mycursor.execute(InsertSql,VAL0)
    
    DB_Connection.commit();        

【问题讨论】:

    标签: python excel pandas slice


    【解决方案1】:

    关于 1)

    read_excel函数的sheet_name参数可以是None。这样做时,返回值将不是 pandas DataFrame,而是字典。它的键将是工作表名称和 DataFrame 本身的值。

    然后您可以遍历该字典并进行检查。

    【讨论】:

      猜你喜欢
      • 2021-03-06
      • 2019-07-27
      • 1970-01-01
      • 2016-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 2011-03-09
      相关资源
      最近更新 更多