我正在尝试设置一种简单的方法来通过 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")
我是一名优秀的程序员,十分优秀!