使用 openpyxl 和 Path 我的目標是:創建多個多行 .txt 檔案,然后將 .txt 內容插入到 .xlsx 檔案中,確保檔案 1 在第 1 列中,并且每行都有自己的行。
我想創建一個嵌套串列,然后回圈遍歷它以插入文本。我不知道如何確保顯示所有嵌套串列字串。這就是我到目前為止所擁有的,幾乎可以滿足我的要求,但這只是第一行文本的重復。
from pathlib import Path
import openpyxl
listOfText = []
wb = openpyxl.Workbook() # Create a new workbook to insert the text files
sheet = wb.active
for txtFile in range(5): # create 5 text files
createTextFile = Path('textFile' str(txtFile) '.txt')
createTextFile.write_text(f'''Hello, this is a multiple line text file.
My Name is x.
This is text file {txtFile}.''')
readTxtFile = open(createTextFile)
listOfText.append(readTxtFile.readlines()) # nest the list from each text file into a parent list
textFileList = len(listOfText[txtFile]) # get the number of lines of text from the file. They are all 3 as made above
# Each column displays text from each text file
for row in range(1, txtFile 1):
for col in range(1, textFileList 1):
sheet.cell(row=row, column=col).value = listOfText[txtFile][0]
wb.save('importedTextFiles.xlsx')
輸出為 4 列/4 行。所有這些都說相同的“你好,這是一個多行文本檔案。”
感謝您對此的任何幫助!
uj5u.com熱心網友回復:
問題出在 for 回圈中,在撰寫時,將行更改sheet.cell(row=row, column=col).value = listOfText[txtFile][0]
為 sheet.cell(row=col, column=row).value = listOfText[row-1][col-1]
,它將起作用
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/466431.html
標籤:python-3.x 打开pyxl xlsx
上一篇:如何按特定組的行數過濾資料集?