gpt4 book ai didi

python - 如何在 openpyxl 中每次使用时创建一个新行?

转载 作者:太空宇宙 更新时间:2023-11-03 16:18:42 25 4
gpt4 key购买 nike

我正在尝试设置一种简单的方法来通过 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")

关于python - 如何在 openpyxl 中每次使用时创建一个新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38680073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com