2016-07-31 2 views
1

私は、ビジネスのレコードをPythonプログラムでマークする簡単な方法を設定しようとしていますが、Excelのシート部分にopenpyxlモジュールを使用していて、私は不思議です。私は、プログラムは、Excelシートの次の行を使用します。。ありがとうございました!openpyxlで毎回新しい行を作るには?

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") 

答えて

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") 
+1

これは、おかげで動作します!!!!! +1 –

+0

助けてくれてありがとうございました! – bernie

+0

問題ありません!ありがとうございました! –

関連する問題