如何使用 Python 将数据从 .txt 文件导入到特定的 excel sheet?

How to import data from .txt file to a specifc excel sheet with Python?

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

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

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

在此先感谢所有提供帮助的人。

首先,将 TXT 文件导入 python 中的列表,我假设 TXT 文件是这样的

1

2

3

4

.....

with open(path_txt, "r") as e:
    list1 = [i for i in e]

然后,我们将列表的值粘贴到您需要的工作表上

from openpyxl import load_workbook

wb = load_workbook(path_xlsx)
ws = wb[sheet_name]
ws["A1"] = "values" #just a header
row = 2 #represent the 2 row of the sheet
column = 1 #represent the column "A" of the sheet

for i in list1:
    ws.cell(row=row, column=column).value = i #getting the current cell, and writing the value of the list
    row += 1 #just setting the current to the next

wb.save(path_xlsx)

希望这对你有用。

Pandas 就可以了!

方法: 有一个 sheet 包含文件路径、分隔符、相应的 target sheet names

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

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()

希望对您有所帮助!如果您 运行 遇到任何问题,请告诉我...