我正在尝试通过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")
答案 0 :(得分:1)
您可以在此处使用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")