好吧,伙计,我想答案是我为xlrd(或者,你自己写的)做的这个愚蠢的包装。关键是函数一次将一行读入一个列表中,Python列表会记住它们的填充顺序。包装器生成一个字典,它将Excel工作表的名称映射到该工作表上的一个行列表(我们假设每个工作表有一个表,否则您将不得不进行一般化处理)。每一行都是一个字典,其键是列名。在
对于你,我会读入你的数据,然后做这样的事情(未经测试):import see_below as sb
dict = sb.workbookToDict(your_file)
output = []
this_location = None
for row in dict[relevant_sheet_name]:
output_row = row
if row['Location'] is not None:
this_location = row['Location']
else:
output_row['Location'] = this_location
也许你可以用列表理解来做一些可爱的事情,但我今晚喝了太多酒来愚弄它:)
下面是给读者的包装:
^{pr2}$
作者在这里:import xlwt
def write(workbookDict, colMap, filename):
'''
workbookDict should be a map of sheet names to a list of dictionaries.
Each member of the list should be a mapping of column names to contents,
missing keys are handled with the nullEntry field. colMap should be a
dictionary whose keys are identical tto the sheet names in the workbookDict.
Each value is a list of column names that are assumed to be in order.
If a key exists in the workbookDict that does not exist in the colDict, the
entry in workbookDict will not be written.
'''
workbook = xlwt.Workbook()
for sheet in workbookDict.keys():
worksheet = workbook.add_sheet(sheet)
cols = colMap[sheet]
i = 0
writeCols = True
while i <= len(workbookDict[sheet]):
if writeCols:
for j in range(len(cols)):
if writeCols: # write col headings
worksheet.write(i, j, cols[j])
writeCols = False
else:
for j in range(len(cols)):
worksheet.write(i, j, workbookDict[sheet][(i-1)][cols[j]])
i += 1
workbook.save(filename)
不管怎样,我真的希望这对你有用!在