继续学习台湾洪老师的python+excel新书代码:

1) 按区域输出EXCEL:
  

fn = 'data3_16.xlsx'
wb = openpyxl.load_workbook(fn)
ws = wb.active
range = ws['A1':'E9']
for a, b, c, d, e in range:
    print(f"{a.value} {b.value} {c.value} {d.value} {e.value}")
这里range指定输出A1到E9区域的内容。

也可以:

fn = 'data3_16.xlsx'
wb = openpyxl.load_workbook(fn)
ws = wb.active
for row in ws['A1':'E9']:
    for cell in row:
        print(cell.value, end=' ')
    print()
2) 输出指定列的空间:
   比如下面的,就是输出B到D列的数据。
fn = 'data3_16.xlsx'
wb = openpyxl.load_workbook(fn)
ws = wb.active
data_range = ws['B':'D']
for cols in data_range:
    for cell in cols:
        print(cell.value, end=' ')
    print()
 比如输出3-6行的数据:
  
wb = openpyxl.load_workbook(fn)
ws = wb.active
data_range = ws[3:6]
for rows in data_range:
    for cell in rows:
        print(cell.value, end=' ')
    print()

3) 获得当前工作表的最左上角,最右下角的坐标:
   
wb = openpyxl.load_workbook(fn)
ws = wb.active
print(ws.dimensions)

4) 用append增加数据
  
wb = openpyxl.Workbook()        # 建立空白的工作簿
ws = wb.active                  # 获得目前工作表
row1 = ['数学','物理','化学']   # 定义列表数据
ws.append(row1)                 # 写入列表
row2 = [98, 82, 89]             # 定义列表数据
ws.append(row2)                 # 写入列表
wb.save('out3_27.xlsx')         # 将工作簿储存

5) 在一个工作簿中创建多个sheet
   
ws1 = wb.active
ws1.title = "DataRange"
for row in range(1, 20):
    ws1.append(range(500))
ws2 = wb.create_sheet(title="School")
ws2['F5'] = "明志科技大学"
ws3 = wb.create_sheet(title="Data")

6) 把工作薄的工作表复制到不同的工作薄
   
fn = "data4_2.xlsx"                     # 来源工作簿
wb = openpyxl.load_workbook(fn)
ws = wb.active
dst = "data4_4.xlsx"
new_wb = openpyxl.load_workbook(dst)    # 开启目的工作簿
new_ws = new_wb.create_sheet(title="新SPA客户表")
for data in ws.iter_rows(min_row=1,max_row=ws.max_row,
            min_col=1,max_col=ws.max_column, values_only=True):
    value = list(data)
    new_ws.append(value)        # 写入目的工作簿

new_wb.save("out4_4.xlsx")      # 用新工作簿储存结果

7) 把工作薄的所有工作表复制到另外一个工作薄
  ,假设某个工作薄有4个SHEET,则:

n1 = "data4_5.xlsx"                    # 来源工作簿
wb = openpyxl.load_workbook(fn1)
fn2 = "dst4_5.xlsx"
new_wb = openpyxl.load_workbook(fn2)    # 建立目的工作簿
for i in range(4):
    ws = wb.worksheets[i]
    dst_title = ws.title    
    new_ws = new_wb.create_sheet(title=dst_title)
    for data in ws.iter_rows(min_row=1,max_row=ws.max_row,
            min_col=1,max_col=ws.max_column, values_only=True):
        value = list(data)
        new_ws.append(value)            # 写入目的工作簿    
new_wb.save("out4_5.xlsx")              # 储存结果
04-06 09:56