六、现有文件的引用和操作(行操作)
6、现有文件的引用和操作(行操作)#coding=utf-8from openpyxl import Workbookfrom openpyxl import load_workbookwb = load_workbook('e:\\sample.xlsx')ws=wb.activerows=[]for row in ws.iter_rows(): rows.append(row)print (rows) #所有行print (rows[0]) #获取第一行print (rows[0][0]) #获取第一行第一列的单元格对象print (rows[0][0].value) #获取第一行第一列的单元格对象的值print (rows[len(rows)-1]) #获取最后行print (rows[len(rows)-1][len(rows[0])-1]) #获取第后一行和最后一列的单元格对象print (rows[len(rows)-1][len(rows[0])-1].value) #获取第后一行和最后一列的单元格对象的值
七、现有文件的引用和操作(列操作)
#coding=utf-8from openpyxl import Workbookfrom openpyxl import load_workbookwb = load_workbook('e:\\sample.xlsx')ws=wb.activecols=[]cols = []for col in ws.iter_cols(): cols.append(col)print (cols) #所有列print (cols[0]) #获取第一列print (cols[0][0]) #获取第一列的第一行的单元格对象print (cols[0][0].value) #获取第一列的第一行的值print ("*"*30)print (cols[len(cols)-1]) #获取最后一列print (cols[len(cols)-1][len(cols[0])-1]) #获取最后一列的最后一行的单元格对象print (cols[len(cols)-1][len(cols[0])-1].value) #获取最后一列的最后一行的单元格对象的值
八、查看格式
# -*- coding: utf-8 -*-from openpyxl import Workbookfrom openpyxl import load_workbookimport datetimewb = load_workbook('e:\\sample.xlsx')ws=wb.activewb.guess_types = True#猜测格式类型
ws["A1"]=datetime.datetime(2010, 7, 21)print (ws["A1"].number_format)ws["A2"]="12%"print (ws["A2"].number_format)ws["A3"]= 1.1print (ws["A3"].number_format)ws["A4"]= "中国"print (ws["A4"].number_format)# Save the filewb.save("e:\\sample.xlsx")
运行结果:
九、打印公式的内容
(因为是excel执行的,打印的东西是公式)
from openpyxl import Workbookfrom openpyxl import load_workbookwb = load_workbook('e:\\sample.xlsx')ws1=wb.activews1["A1"]=1ws1["A2"]=2ws1["A3"]=3ws1["A4"] = "=SUM(1, 1)"ws1["A5"] = "=SUM(A1:A3)"print (ws1["A4"].value) #打印的是公式内容,不是公式计算后的值,程序无法取到计算后的值print (ws1["A5"].value) #打印的是公式内容,不是公式计算后的值,程序无法取到计算后的值# Save the filewb.save("e:\\sample.xlsx")
十、合并/拆分单元格
# -*- coding: utf-8 -*-from openpyxl import Workbookfrom openpyxl import load_workbookwb = load_workbook('e:\\sample.xlsx')ws1=wb.activefrom openpyxl.workbook import Workbookwb = Workbook()ws = wb.activews.merge_cells('A2:D2')#合并ws.unmerge_cells('A2:D2')#拆分# or equivalentlyws.merge_cells(start_row=2,start_column=1,end_row=2,end_column=4)#合并相关ws.unmerge_cells(start_row=2,start_column=1,end_row=2,end_column=4)#拆分相关# Save the filewb.save("e:\\sample.xlsx")