簡體   English   中英

如何使用 Python 將 .txt 文件中的數據導入特定的 Excel 工作表?

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

我正在嘗試自動化一個基本上將文本文件中的值讀入某些 Excel 單元格的過程。 我在 excel 中有一個模板,可以從特定名稱的各種工作表中讀取數據。 例如,模板將從“視頻分數”中讀取數據。 視頻分數是一個 .txt 文件,我將其復制並粘貼到 excel 中。 每個項目中使用了 5 個不同的文本文件,因此一段時間后以及有很多項目要完成時,它會變得乏味。

如何將這些 .txt 文件導入或復制並粘貼到 excel 中到指定的工作表? 我一直在為這個項目的其他部分使用 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 讀取這個 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()

希望這可以幫助! 如果您遇到任何問題,請告訴我...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM