有没有办法将多张Excel文件作为“csv”输入到PostgreSQL中?

问题描述 投票:0回答:2

我的任务是将公司的数据存储在数据库中,我正在使用 PostgreSQL。我正在使用 python 访问 PostgreSQL 并与之交互。到目前为止,我的问题是我有多个 Excel 数据集,这些数据集非常复杂且庞大,有多个工作表(即每个 Excel 文件最多 20 个工作表)。这些都是“xlsx”格式,我试图将它们以“csv”格式输入到数据库中的表中。我尝试使用 pandas 转换为 csv 并将每个 excel 文件转换为 csv 格式。但是,存在许多 NaN 值、添加了未命名的列,并且输出 csv 文件的列与其关联的数据行不相关。它变得非常混乱并且组织不正确。

关于如何使用具有多个工作表的 Excel 文件从“xlsx”转换为“csv”有什么想法吗?

谢谢!

我尝试使用 pandas 将 excel“xlsx”文件转换为“csv”文件。我得到了 csv 文件的输出,但是,打开它后,我看到添加了一个未命名的列、NaN 以及与正确关联的数据行不对应的列。总之,输出的 csv 文件非常混乱,并且不能正确描述原始 Excel 电子表格中包含的信息。

python excel postgresql csv xlsx
2个回答
0
投票

您可以使用以下代码模式将 Excel 工作表中的数据加载到 Postgres 数据库

import pandas as pd
from sqlalchemy import create_engine

# Replace these with your PostgreSQL connection details
username = 'your_username'
password = 'your_password'
host = 'localhost'
port = '5432'
database = 'your_database'

# Path to your Excel file
excel_file = 'path_to_your_excel_file.xlsx'

# Create a SQLAlchemy engine
engine = create_engine(f'postgresql+psycopg2://{username}:{password}@{host}:{port}/{database}')

# Read the Excel file
xls = pd.ExcelFile(excel_file)

# Loop through each sheet
for sheet_name in xls.sheet_names:
# Read each sheet to a DataFrame
    df = pd.read_excel(xls, sheet_name)

    # Load DataFrame into PostgreSQL table, replace 'your_table_name' with your actual table name
    # The name of the table will be the same as the sheet name
    df.to_sql(sheet_name, engine, if_exists='replace', index=False)

print("Data loaded successfully.")

0
投票
import pandas as pd

def convert_excel_to_csv(excel_file):
    xls = pd.ExcelFile(excel_file)
    for sheet_name in xls.sheet_names:
        df = pd.read_excel(xls, sheet_name)
        df = df.dropna(how='all')  # Handling NaN by dropping all row filled with NaN and if not all filled then replacing with empty string as per ask and removed Unnamed column
        df = df.fillna('')  
        df = df.loc[:, ~df.columns.str.contains('^Unnamed')]  
        csv_file = f"{excel_file}_{sheet_name}.csv"
        df.to_csv(csv_file, index=False)
        print(f"Created CSV for sheet: {sheet_name}")
path_to
convert_excel_to_csv('path_to_exccel.xlsx')

这将创建名为

excel_file_path_sheet_name

的文件
© www.soinside.com 2019 - 2024. All rights reserved.