首页 > 解决方案 > 如何使用 Python 将 .txt 文件中的数据导入特定的 excel 工作表?

问题描述

我正在尝试自动化一个基本上将文本文件中的值读入某些 excel 单元格的过程。我在 excel 中有一个模板,它将以特定名称从各种工作表中读取数据。例如,模板将从“视频分数”中读取数据。视频乐谱是一个 .txt 文件,我将其复制并粘贴到 Excel 中。每个项目中使用了 5 个不同的文本文件,因此在一段时间后以及有很多项目要完成时,它会变得乏味。

如何将这些 .txt 文件导入或复制并粘贴到 excel 到指定的工作表中?我一直在将 openpyxl 用于该项目的其他部分,但如果无法使用 openpxl 完成,我愿意使用另一个库。

我也尝试过打开和读取文件,但我也不知道如何做我想做的事。我找到了我需要的所有文件的列表,只需将它们放入 excel 即可。

提前感谢任何提供帮助的人。

标签: pythonopenpyxl

解决方案


熊猫会做的伎俩!

方法: 有一张包含文件路径、分隔符、相应目标工作表名称的工作表

现在使用 pandas 读取此 excel 表并遍历每个文件详细信息的每一行,读取数据,将其写入同一工作簿的新 excel 表。

import pandas as pd

file_details_path = r"/Users/path for xl sheet/file details/File2XlDetails.xlsx"
target_sheet_path = r"/Users/path to target xl sheet/File samples/FiletoXl.xlsx"

# create a writer to save the file content in excel
writer = pd.ExcelWriter(target_sheet_path, engine='xlsxwriter')


file_details = pd.read_excel(file_details_path,
                             dtype = str,
                             index_col = False
                             )


def write_to_excel(file, trg_sheet_name):
    # writes it to excel
    file.to_excel(writer,
                  sheet_name = trg_sheet_name,
                  index = False,
                  )

# loop through each file record
for index, file_dtl in file_details.iterrows():

    # you can print and check the row content for reference
    print(file_dtl['File_path'])
    print(file_dtl['Separator'])
    print(file_dtl['Target_sheet_name'])

    # reads file
    file = pd.read_csv(file_dtl['File_path'],
                       sep = file_dtl['Separator'],
                       dtype = str,
                       index_col = False,
                       )
    write_to_excel(file, file_dtl['Target_sheet_name'])

writer.save()

希望这可以帮助!如果您遇到任何问题,请告诉我...


推荐阅读