Py学习  »  DATABASE

将多个Excel工作表加载到MySQL中

kumarm • 4 年前 • 690 次点击  

我有多个excel文件,inturn中有多个工作表我正试图将它们加载到mysql数据库中 下面是我的excel工作代码

import pandas as pd
    df = pd.read_excel(open(path+ "/" +file, 'rb'), sheet_name='Sheet1')
                      table_name = "sample"
                      # Defaulting null values to 0 .
                   df=df.fillna(0)
                 # inserting the data.
                   df.to_sql(con=engine, name=table_name, if_exists='replace', schema=None)

上面的代码可以工作,但有一个问题 1。我正在硬编码的表名理想情况下,我想有相同的名称,我可能会使用拆分和只得到文件名是有更好的方式来获得文件名没有扩展名。

但真正的问题是

现在在我的文件夹中可以有多个excel文件,其中包含多个工作表 示例document1.xlsx(其中有两张sheet1和sheet2) 我就是这么做的

    xls = pd.ExcelFile('document1.xlsx')
                sheets = []
                sheets = xls.sheet_names
                #type(sheets)
                #print(sheets)this gives me list containing sheet1,sheet2
                for i in sheets:
                    #print(i) 
                    df = pd.read_excel(open(path+ "/" +file, 'rb'), sheet_name=i)
   df.to_sql(con=engine, name=table_name, if_exists='replace', schema=None)

在上面的代码中,数据框保存了两张表的数据,但是我想存储表1的数据,首先将其加载到一个表中,然后将第二张表加载到另一个表中,所以在上面的df中,我做了这个更改,以查看代码是否工作 读excel(open(path+“/”+file,'rb'),sheet_name=i[0])但它没有任何效果??

谢谢你

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40387
 
690 次点击  
文章 [ 2 ]  |  最新文章 4 年前
kumarm
Reply   •   1 楼
kumarm    5 年前

@ RyGuy72 代码看起来像这样

xls = pd.ExcelFile(path + "/" + file)
                  #Create a list which consists of all sheet names in a Excel file.
                  sheets = []# declaring empty list
                  sheets = xls.sheet_names # getting sheet names
                  ex_op = open(path +"/" + file, 'rb')# opening the Excel sheets
                  for i in sheets:
                      # Passing the sheet names as table names.
                      table_name = i
                      #read that sheet that is being processed
                      df = pd.read_excel(ex_op, sheet_name=i)
                      # Defaulting null values to 0 to be confirmed.
                      df=df.fillna(0)
                      #Droping and recreating the table and inserting the data.
                      df.to_sql(con=engine, name=table_name, if_exists='replace', schema=None)
                  # Close the Excel file.
                  ex_op.close()

这段代码满足了我的需求,可以编辑它来做很多其他的事情。

ryguy72
Reply   •   2 楼
ryguy72    5 年前

这肯定不是python的答案,但是如果您可以使用其他工具,我建议您这样做。

https://www.rondebruin.nl/win/addins/rdbmerge.htm

使用加载项,将所有文件(文件夹中)中的所有工作表合并到一个主数据集中。然后,将其推送到mysql中,或者使用工作台将其导入到mysql中。很高兴看到python这样做,但如果您正处于时间紧迫的情况下,只想完成这项工作,请尝试我在这里推荐的方法。