2017-06-11 23 views
0

Excel用のスプレッドシートの各セルを循環するforループを作成しようとしています。そのシートからデータを取り出し、それをリストに入れます。エクセルシートを循環するPython forループ

次に、ループを繰り返し実行してリストを繰り返し、データを別のシートに配布します。

私は個々にそれを個別に行うことができることを知っています。これは私のコードで今あるものです。

import openpyxl 
import xlrd 
import xlwt 
wb = openpyxl.load_workbook('Z:\Public\Safety\SafetyDataPullProject\TestFile.xlsx') 
type(wb) 
sheet = wb.get_sheet_by_name('Sheet1') 
a = sheet['E5'] 

#Data From Old Sheets 
wb = openpyxl.load_workbook('Z:\Public\Safety\SafetyDataPullProject\TestFile.xlsx') 
type(wb) 
sheet = wb.get_sheet_by_name('Sheet1') 




#New Excel Sheet Creation 
book = xlwt.Workbook(encoding="utf-8") 
sheet1 = book.add_sheet("Current") 
sheet1.write(0, 0, "BFI4 AM CARE EOS REPORT", style0) 
sheet1.write(0, 6,(time.strftime("%d/%m/%Y")), style0) 

sheet1.write(1, 0, 'Encounter Type', style1) 
sheet1.write(1, 3, "Day Shift", style1) 
sheet1.write(1, 4, "Night Shift", style1) 
sheet1.write(1, 5, "Totals", style1) 
sheet1.write(1, 6, "WTD", style1) 


sheet1.write(5, 3, "Day Shift", style1) 
sheet1.write(5, 4, "Night Shift", style1) 
sheet1.write(5, 5, "Totals", style1) 
sheet1.write(5, 6, "WTD", style1) 

sheet1.write(2, 0 , "New Wrk Related Injury",style1) 
sheet1.write(2, 3 , a.value) 
sheet1.write(3, 0 , "Wrk Related Follow-up") 
sheet1.write(4, 0 , "Missed Follow-up") 

答えて

0

openpyxlですべてをやって、この例を考えてみましょう:

のPythonでテスト
# Old Sheet 
ws = wb.get_sheet_by_name('Sheet1') 

from openpyxl.styles import Font, colors, PatternFill 
style = {'font': Font(color=colors.BLACK)} 
style1 = {'font':Font(color=colors.WHITE, bold=True,italic=True), 
      'fill':PatternFill(start_color=colors.RED,end_color=colors.RED,fill_type='solid') 
     } 

data = [ 
    ["BFI4 AM CARE EOS REPORT", '', '', '', '', '', (time.strftime("%d/%m/%Y"))], 
    ['Encounter Type', '', '', "Day Shift", "Night Shift", "Totals", "WTD"], 
    ["New Wrk Related Injury", '', '', '', '', '', ''], 
    ["Wrk Related Follow-up", '', '', '', '', '', ''], 
    ["Missed Follow-up", '', '', '', '', '', ''], 
    ['', '', '', "Day Shift", "Night Shift", "Totals", "WTD"] 
    ] 

# Copy Data From Old Sheet 
for dRow in range(2, 5): 
    for dCol in range(3, 7): 
     data[dRow][dCol] = ws.cell(row=dRow+3, column=dCol+2).value 

# New Sheet Creation 
ws1 = wb.create_sheet("Current") 
for row, rData in enumerate(data, 1): 
    ws1.append(rData) 
    for c, rD in enumerate(rData,1): 
     cell = ws1.cell(row=row, column=c) 
     if row == 1: 
      cell.font = style1['font'] 
      cell.fill = style1['fill'] 
     else: 
      cell.font = style['font'] 

wb.save('test.xlsx') 

を:3.4.2 - openpyxl:2.4.1 - LibreOfficeの:4.3.3.2

+0

感謝あなたは非常に@stovfl !!あなたは私がこれを理解するのを助けることができると思いますか?私はそれを追加して、リスト内のstrをintに変更したいので、別のシートから引っ張って、セル内の何にでも追加することができます。私はこのコードを見て、ちょっと混乱しているので、私はできないように感じる。 –

+0

'string'や' int'を使っても違いはありません。 'int'を引くと、' openpyxl'は 'int'と書かれます。 – stovfl

関連する問題