我有两个 xls 文件,每行都属于彼此。我打算制作一个文本文件,将第二行放在那里,并用第一行命名。示例数据如下所示
data1.xls
ram
rama
rot
tab
data2.xls
myfirstattemp
mysecondattemp
mythirdattemp
myfourthattemp
所以它看起来像这样
ram.txt (inside is myfirstattempt)
rama.txt (inside is mysecondattemp)
.
.
.
我确实尝试了不同的东西,但我无法弄清楚,看看我写了什么
import xlrd
workbook1 = xlrd.open_workbook('data1.xlsx')
workbook2 = xlrd.open_workbook('data2.xlsx')
for sheet in workbook1.sheets():
for i in range(sheet.nrows):
for sheet in workbook2.sheets():
for i in range(sheet.nrows):
rowi_col0 = sheet.cell_value(i, 0)
#print filename.format(col_0, i)
out.save(workbook1.format('sheet.nrows', i+1))
答案 0 :(得分:0)
你还没有说明你的错误信息是什么,所以我不得不指定一个过程。此外,您的 out.save
行将崩溃,因为没有对 out
的引用。
请注意,出于安全原因,不建议将 xlrd 用于 xlsx,仅用于 xls。建议您为 xlsx 使用像 openpyxl 这样的库。 (实际上,如果您拥有最新版本的 xlrd,它甚至不会让您针对 xlsx 运行 - 因此我的代码指的是 xls)。
import xlrd
# Set the references to the workbook and sheets
workbook1 = xlrd.open_workbook('data1.xls')
workbook2 = xlrd.open_workbook('data2.xls')
sheet1 = workbook1.sheet_by_index(0)
sheet2 = workbook2.sheet_by_index(0)
# Pull the data into lists
names_for_files = [sheet1.cell_value(row,0) for row in range(sheet1.nrows)]
data_for_files = [sheet2.cell_value(row,0) for row in range(sheet2.nrows)]
# Iterate over the names
for out_index,output_name in enumerate(names_for_files):
with open(f'{output_name}.txt', 'w') as f:
f.write(data_for_files[out_index])
# Could zip the two lists together to tidy up the output
# Could pull the data as a dictionary for the same reason