从 excel (.xlsx) 中提取并写入 .txt 文件

Extracting from excel (.xlsx) writing to .txt file

背景:Excel 文件有 3 列和大约 10,000 行。列:姓名、地址和电子邮件。对应数据的行。

尝试使用以下代码提取 excel 文件中的每个条目,并使用此人的姓名保存在单独的文件中。就像一个"business card"。

.txt 文件已生成,但它们是空的 -- 即没有数据写入文件。

代码哪里出错了,我该如何解决?

import openpyxl as opx
from openpyxl import load_workbook

fileName = r'\...\Name Extraction Text files\TestBook.xlsx'
sheetName = "Sheet1"

wb2 = load_workbook(fileName)
ws4 = wb2["Sheet1"]

maxRows = sheet.max_row
>>> 10001
maxCol = sheet.max_column
>>> 3

for i in range(1, maxRows + 1):
    name = sheet.cell(row=i, column=1).value
    outputFile = open(r'\...\ExtractedFiles\{}.txt'.format(name), 'w')

for j in range(1, maxCol + 1):
    outputFile.write(sheet.cell(row=i, column=j).value + '\n')
    outputFile.seek(0)

#checking for the count
print('Written file number: {}'.format(i))

print('Done writing your business cards.')

编辑:首先尝试使用 .close() 函数,但给出错误 I/O operation on closed file. 所以这次尝试使用 .seek(0).

我假设您想为每一行制作一个 txt 文件?在执行另一个文件之前,您需要关闭已写入的文件。

outputFile.close()

您可能还想为 open 函数提供 'w+'。

看看这个 https://www.guru99.com/reading-and-writing-files-in-python.html

添加:

for i in range(1, maxRows + 1):
    name = ws4.cell(row=i, column=1).value
    outputFile = open('test{}.txt'.format(name), 'w+')
    for j in range(1, maxCol + 1):
        outputFile.write(ws4.cell(row=i, column=j).value + "\n")
    outputFile.close()

第二个 for 循环在第一个循环之外。它需要在第一个 for 循环内。