从.xlsx列中读取数据,并使用python将每个列另存为单独的.txt文件



我需要用python制作一个脚本,一次从文件中读取一列.xlsx并将每个列的数据保存在新的.txt文件中,并具有连续名称,如(file1.txt,file2.txt...( 我有脚本的某些部分,但无法将它们组合在一起。

用于选择数据的脚本的一部分:

for i in range(1, m_row + 1):
cell_obj = sheet_obj.cell(row=i, column=j+1)
print(cell_obj.value)
print(cell_obj.value, file=open(
file.txt',
'a'))

对于命名文件:

while i: 
i+=1
try:
with open('output{}.txt'.format(i), 'x'): 
break
except PermissionError:
continue

已求解:

此脚本有效。键是缩进第二个语句

import openpyxl
path = "input.xlsm"
wb_obj = openpyxl.load_workbook(path)
sheet_obj = wb_obj.active
m_row = sheet_obj.max_row
m_col = sheet_obj.max_column
for j in range(1, m_col + 1):
name = sheet_obj.cell(row=2200, column=j).value
outputFile = open(r'file.{}.txt'.format(name), 'w')
for i in range(1, m_row + 1):
cell_obj = sheet_obj.cell(row=i, column=j)
print(cell_obj.value, file=outputFile)
outputFile.close()

最新更新