如何在openpyxl中使用每一行?

我试图设置一个简单的方法来标记我的业务logging通过python程序,我使用模块openpyxl excel表部分,我想知道如何我可以使它每次我使用它使用的程序在Excel表格中的下一行 。 谢谢!

from openpyxl import Workbook wb = Workbook() # grab the active worksheet ws = wb.active item = raw_input('Item: ') sold = raw_input('Sold for: ') percentage = raw_input('Percentage (in decimals): ') date = raw_input('Date of Sale: ') customer = raw_input('Customer: ') # Data can be assigned directly to cells ws['B2'] = item ws['C2'] = sold ws['D2'] = percentage ws['E2'] = date ws['F2'] = customer wb.save("sample.xlsx") 

你可以在这里使用ws.max_row 。 另外请确保您加载以前保存的文件,而不是每次打开一个新的文件。

 import openpyxl wb = openpyxl.load_workbook('sample.xlsx') # grab the active worksheet ws = wb.active item = raw_input('Item: ') sold = raw_input('Sold for: ') percentage = raw_input('Percentage (in decimals): ') date = raw_input('Date of Sale: ') customer = raw_input('Customer: ') # Data can be assigned directly to cells input_row = ws.max_row + 1 ws['B{}'.format(input_row)] = item ws['C{}'.format(input_row)] = sold ws['D{}'.format(input_row)] = percentage ws['E{}'.format(input_row)] = date ws['F{}'.format(input_row)] = customer wb.save("sample.xlsx") 

你也可以考虑在这里实现一个while循环:

 import openpyxl enter_more = 'y' while enter_more == 'y': wb = openpyxl.load_workbook('sample.xlsx') # grab the active worksheet ws = wb.active item = raw_input('Item: ') sold = raw_input('Sold for: ') percentage = raw_input('Percentage (in decimals): ') date = raw_input('Date of Sale: ') customer = raw_input('Customer: ') # Data can be assigned directly to cells input_row = ws.max_row + 1 ws['B{}'.format(input_row)] = item ws['C{}'.format(input_row)] = sold ws['D{}'.format(input_row)] = percentage ws['E{}'.format(input_row)] = date ws['F{}'.format(input_row)] = customer wb.save("sample.xlsx") enter_more = raw_input('Enter "y" to enter more data...').lower() 

编辑:
正如@CharlieClark在评论中提到的,你可以使用.append()

 import openpyxl wb = openpyxl.load_workbook('sample.xlsx') # grab the active worksheet ws = wb.active item = raw_input('Item: ') sold = raw_input('Sold for: ') percentage = raw_input('Percentage (in decimals): ') date = raw_input('Date of Sale: ') customer = raw_input('Customer: ') # Data can be assigned directly to cells ws.append([None, item, sold, percentage, date customer]) wb.save("sample.xlsx")