循环遍历Excel工作表的Python for循环

时间:2017-06-11 11:13:25

标签: python excel

我正在尝试创建一个循环遍历excel电子表格的每个Cell的for循环。从该工作表中提取数据,然后将其放入列表中。

然后是一个单独的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")

1 个答案:

答案 0 :(得分:0)

考虑这个例子,使用openpyxl执行所有操作:

# 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')

使用Python测试:3.4.2 - openpyxl:2.4.1 - LibreOffice:4.3.3.2