使用Python和Openpyxl循环一个.xlsx,但循环只保存最后一行的数据

我是一个Python的新手,我正在一个项目,以自动化一个非常耗时的项目。 我使用的是openpyxl来访问.xlsx来提取信息,最终将转换成距离和方向轴承与arcpy / arcgis一起使用,这意味着我正在使用Python 2.7。 我可以访问数据并进行第一轮更改,但无法将我的写入命令集成到我的循环中。 目前它将最后一行的数据保存到新的.xlsx中给定范围内的所有单元格中。 这是我的代码:

#Importing OpenPyXl and loads the workbook and sheet import openpyxl wb = openpyxl.load_workbook('TESTVECT.xlsx') ws = wb.get_sheet_by_name('TEST') #allows to save more than once write_only = False cell_range = ws['C'] #sorts through either the rows/columns and slices the required string maxRow = ws.max_row + 1 for row in range(2, maxRow): parID = ws['A' + str(row)].value Lline = ws['B' + str(row)].value Vect = ws['C' + str(row)].value print parID, Lline, Vect trash, keep = Vect.split("C") #This part save the very last row to all rows in available columns #need a way to integrate the save functionality so each row is unique for rowNum in range(2, maxRow): ws.cell(row=rowNum, column=3).value = keep for rowNum in range (2, maxRow): ws.cell(row=rowNum, column=1).value = parID for rowNum in range (2, maxRow): ws.cell(row=rowNum, column=2).value = Lline #Only prints the very last keep entry from the .xlsx print keep print "all done" #Saving does not write all of the the 'keep, parID, and Lline' records #There is an issue with the for loop and integrating the write portion of #the code. wb.save('TESTMONKEYVECT.xlsx') 

有人可以给我一些指针,说明我在做什么错误的写入过程中,我需要每行保留其独特的数据后,已经作出的更改。

谢谢,

你的直觉是正确的,你需要结合循环。 第一个循环遍历每一行,并保存parID Lline ,并keep每个variables的最后一个值。 在循环之后,它们只有最后一行的值,因为那是唯一的一行,没有另外一行出现并重写值。

您可以通过将这些操作组合到一个循环中来解决这个问题。

 maxRow = ws.max_row + 1 for row in range(2, maxRow): parID = ws['A' + str(row)].value Lline = ws['B' + str(row)].value Vect = ws['C' + str(row)].value print parID, Lline, Vect trash, keep = Vect.split("C") ws.cell(row=rowNum, column=3).value = keep ws.cell(row=rowNum, column=1).value = parID ws.cell(row=rowNum, column=2).value = Lline