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

时间:2016-10-26 16:52:28

标签: python excel openpyxl

我是一个Python newb,我正在开发一个项目来自动化一个非常耗时的项目。我正在使用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')

有人可以给我一些关于我在写入过程中做错的指示,我需要每行在更改完成后保留其唯一数据。

谢谢,

2 个答案:

答案 0 :(得分:0)

你的直觉是正确的,你需要结合循环。第一个循环遍历每一行,并将parIDLlinekeep保存在每个变量的最后一个值上。在循环之后,它们只有最后一行的值,因为这是唯一一条在它之后没有另一行并覆盖它们的行。

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

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

答案 1 :(得分:0)

对不起,我对这个话题还很陌生-但这个例子可能会有所帮助:

#create loop to read from column of opened file and print from specific column row by row
i = 1
while i <= row_count:
    ws_write.cell(row=i, column=col_write, value=sheet_read.cell(i, col_read).value)
    i += 1

基本上,您需要将值分配给循环内的单元格-正如先前的答案已经指出的