pip install openpyxl
想要在文件中插入图片文件,需要安装pillow,安装文件:PIL-fork-1.1.7.win-amd64-py2.7.exe
· font(字体类):字号、字体颜色、下划线等
· fill(填充类):颜色等
· border(边框类):设置单元格边框
· alignment(位置类):对齐方式
· number_format(格式类):数据格式
· protection(保护类):写保护
# -*- coding: utf-8 -*-from openpyxl import Workbookwb = Workbook()ws1 = wb.create_sheet("Mysheet") #创建一个sheetws1.title = "New Title" #设定一个sheet的名字ws2 = wb.create_sheet("Mysheet", 0) #设定sheet的插入位置 默认插在后面ws2.title = u"你好" #设定一个sheet的名字 必须是Unicodews1.sheet_properties.tabColor = "1072BA" #设定sheet的标签的背景颜色#获取某个sheet对象print wb.get_sheet_by_name(u"你好" )print wb["New Title" ]#获取全部sheet 的名字,遍历sheet名字print wb.sheetnamesfor sheet_name in wb.sheetnames: print sheet_nameprint "*"*50for sheet in wb: print sheet.title#复制一个sheetwb["New Title" ]["A1"]="zeke"source = wb["New Title" ]target = wb.copy_worksheet(source)# w3 = wb.copy_worksheet(wb['new title'])# ws3.title = 'new2'# wb.copy_worksheet(wb['new title']).title = 'hello'# Save the filewb.save("e:\\sample.xlsx")
# -*- coding: utf-8 -*-from openpyxl import Workbookwb = Workbook()ws1 = wb.create_sheet("Mysheet") #创建一个sheetws1["A1"]=123.11ws1["B2"]="你好"d = ws1.cell(row=4, column=2, value=10)print ws1["A1"].valueprint ws1["B2"].valueprint d.value# Save the filewb.save("e:\\sample.xlsx")
无论ws.rows还是ws.iter_rows都是一个对象
除上述两个对象外 单行,单列都是一个元祖,多行多列是二维元祖
# -*- coding: utf-8 -*-from openpyxl import Workbookwb = Workbook()ws1 = wb.create_sheet("Mysheet") #创建一个sheetws1["A1"]=1ws1["A2"]=2ws1["A3"]=3ws1["B1"]=4ws1["B2"]=5ws1["B3"]=6ws1["C1"]=7ws1["C2"]=8ws1["C3"]=9#操作单列print ws1["A"]for cell in ws1["A"]: print cell.value#操作多列,获取每一个值print ws1["A:C"]for column in ws1["A:C"]: for cell in column: print cell.value#操作多行row_range = ws1[1:3]print row_rangefor row in row_range: for cell in row: print cell.valueprint "*"*50for row in ws1.iter_rows(min_row=1, min_col=1, max_col=3, max_row=3): for cell in row: print cell.value#获取所有行print ws1.rowsfor row in ws1.rows: print rowprint "*"*50#获取所有列print ws1.columnsfor col in ws1.columns: print colwb.save("e:\\sample.xlsx")
使用百分数
# -*- coding: utf-8 -*-from openpyxl import Workbookfrom openpyxl import load_workbookwb = load_workbook('e:\\sample.xlsx')wb.guess_types = Truews=wb.activews["D1"]="12%"print ws["D1"].value# Save the filewb.save("e:\\sample.xlsx")#结果会打印小数
# -*- coding: utf-8 -*-from openpyxl import Workbookfrom openpyxl import load_workbookwb = load_workbook('e:\\sample.xlsx')wb.guess_types = Falsews=wb.activews["D1"]="12%"print ws["D1"].valuewb.save("e:\\sample.xlsx")#结果会打印百分数
#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[-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 "*"*30print 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_workbookwb = load_workbook('e:\\sample.xlsx')wb.guess_types = True #猜测格式类型ws=wb.activews["D1"]="12%"print ws["D1"].value# Save the filewb.save("e:\\sample.xlsx")#注意如果原文件有一些图片或者图标,则保存的时候可能会导致图片丢失
# -*- coding: utf-8 -*-from openpyxl import Workbookfrom openpyxl import load_workbookimport datetimewb = load_workbook('e:\\sample.xlsx')ws=wb.activewb.guess_types = Truews["A1"]=datetime.datetime(2010, 7, 21)print ws["A1"].number_formatws["A2"]="12%"print ws["A2"].number_formatws["A3"]= 1.1print ws["A4"].number_formatws["A4"]= "中国"print ws["A5"].number_format# Save the filewb.save("e:\\sample.xlsx")执行结果:yyyy-mm-dd h:mm:ss0%GeneralGeneral#如果是常规,显示general,如果是数字,显示'0.00_ ',如果是百分数显示0%数字需要在Excel中设置数字类型,直接写入的数字是常规类型
# -*- coding: utf-8 -*-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.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")
需要先安装Pilow,安全文件是:PIL-fork-1.1.7.win-amd64-py2.7.exe
# -*- coding: utf-8 -*-from openpyxl import load_workbookfrom openpyxl.drawing.image import Imagewb = load_workbook('e:\\sample.xlsx')ws1=wb.activeimg = Image('e:\\1.png')ws1.add_image(img, 'A1')# Save the filewb.save("e:\\sample.xlsx")
# -*- coding: utf-8 -*-from openpyxl import load_workbookfrom openpyxl.drawing.image import Imagewb = load_workbook('e:\\sample.xlsx')ws1=wb.activews1.column_dimensions.group('A', 'D', hidden=True) #隐藏a到d列范围内的列#ws1.row_dimensions 无group方法# Save the filewb.save("e:\\sample.xlsx")
12、 画一个柱状图# -*- coding: utf-8 -*-from openpyxl import load_workbookfrom openpyxl import Workbookfrom openpyxl.chart import BarChart, Reference, Serieswb = load_workbook('e:\\sample.xlsx')ws1=wb.activewb = Workbook()ws = wb.activefor i in range(10): ws.append([i])values = Reference(ws, min_col=1, min_row=1, max_col=1, max_row=10)chart = BarChart()chart.add_data(values)ws.add_chart(chart, "E15")# Save the filewb.save("e:\\sample.xlsx")
# -*- coding: utf-8 -*-from openpyxl import load_workbookfrom openpyxl import Workbookfrom openpyxl.chart import (PieChart , ProjectedPieChart, Reference)from openpyxl.chart.series import DataPointdata = [ ['Pie', 'Sold'], ['Apple', 50], ['Cherry', 30], ['Pumpkin', 10], ['Chocolate', 40],]wb = Workbook()ws = wb.activefor row in data: ws.append(row)pie = PieChart()labels = Reference(ws, min_col=1, min_row=2, max_row=5)data = Reference(ws, min_col=2, min_row=1, max_row=5)pie.add_data(data, titles_from_data=True)pie.set_categories(labels)pie.title = "Pies sold by category"# Cut the first slice out of the pieslice = DataPoint(idx=0, explosion=20)pie.series[0].data_points = [slice]ws.add_chart(pie, "D1")ws = wb.create_sheet(title="Projection")data = [ ['Page', 'Views'], ['Search', 95], ['Products', 4], ['Offers', 0.5], ['Sales', 0.5],]for row in data: ws.append(row)projected_pie = ProjectedPieChart()projected_pie.type = "pie"projected_pie.splitType = "val" # split by valuelabels = Reference(ws, min_col=1, min_row=2, max_row=5)data = Reference(ws, min_col=2, min_row=1, max_row=5)projected_pie.add_data(data, titles_from_data=True)projected_pie.set_categories(labels)ws.add_chart(projected_pie, "A10")from copy import deepcopyprojected_bar = deepcopy(projected_pie)projected_bar.type = "bar"projected_bar.splitType = 'pos' # split by positionws.add_chart(projected_bar, "A27")# Save the filewb.save("e:\\sample.xlsx")
# -*- coding: utf-8 -*-from openpyxl import load_workbookfrom openpyxl import Workbookfrom openpyxl.worksheet.table import Table, TableStyleInfowb = Workbook()ws = wb.activedata = [ ['Apples', 10000, 5000, 8000, 6000], ['Pears', 2000, 3000, 4000, 5000], ['Bananas', 6000, 6000, 6500, 6000], ['Oranges', 500, 300, 200, 700],]# add column headings. NB. these must be stringsws.append(["Fruit", "2011", "2012", "2013", "2014"])for row in data: ws.append(row)tab = Table(displayName="Table1", ref="A1:E5")# Add a default style with striped rows and banded columnsstyle = TableStyleInfo(name="TableStyleMedium9", showFirstColumn=True, showLastColumn=True, showRowStripes=True, showColumnStripes=True)#第一列是否和样式第一行颜色一行,第二列是否···#是否隔行换色,是否隔列换色tab.tableStyleInfo = stylews.add_table(tab)# Save the filewb.save("e:\\sample.xlsx")
# -*- coding: utf-8 -*-from openpyxl import Workbookfrom openpyxl.styles import colorsfrom openpyxl.styles import Fontwb = Workbook()ws = wb.activea1 = ws['A1']d4 = ws['D4']ft = Font(color=colors.RED) # color="FFBB00",颜色编码也可以设定颜色a1.font = ftd4.font = ft# If you want to change the color of a Font, you need to reassign it::#italic 倾斜字体a1.font = Font(color=colors.RED, italic=True) # the change only affects A1a1.value = "abc"# Save the filewb.save("e:\\sample.xlsx")
# -*- coding: utf-8 -*-from openpyxl import Workbookfrom openpyxl.styles import colorsfrom openpyxl.styles import Fontwb = Workbook()ws = wb.activea1 = ws['A1']d4 = ws['D4']a1.value = "abc"from openpyxl.styles import Fontfrom copy import copyft1 = Font(name=u'宋体', size=14)ft2 = copy(ft1) #复制字体对象ft2.name = "Tahoma"print ft1.nameprint ft2.nameprint ft2.size # copied from thea1.font = ft1# Save the filewb.save("e:\\sample.xlsx")
# -*- coding: utf-8 -*-from openpyxl import Workbookfrom openpyxl.styles import Fontwb = Workbook()ws = wb.activecol = ws.column_dimensions['A']col.font = Font(bold=True) #将A列设定为粗体row = ws.row_dimensions[1]row.font = Font(underline="single") #将第一行设定为下划线格式# Save the filewb.save("e:\\sample.xlsx")
# -*- coding: utf-8 -*-from openpyxl import Workbookfrom openpyxl.styles import Fontfrom openpyxl.styles import NamedStyle, Font, Border, Side,PatternFillwb = Workbook()ws = wb.activehighlight = NamedStyle(name="highlight")highlight.font = Font(bold=True, size=20,color= "ff0100")highlight.fill = PatternFill("solid", fgColor="DDDDDD")#背景填充bd = Side(style='thick', color="000000")highlight.border = Border(left=bd, top=bd, right=bd, bottom=bd)print dir(ws["A1"])ws["A1"].style =highlight# Save the filewb.save("e:\\sample.xlsx")
# -*- coding: utf-8 -*-from openpyxl import Workbookfrom openpyxl.styles import Fontfrom openpyxl.styles import NamedStyle, Font, Border, Side,PatternFillfrom openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Fontwb = Workbook()ws = wb.activeft = Font(name=u'微软雅黑', size=11, bold=False, italic=False, vertAlign=None, underline='none', strike=False, color='FF000000')fill = PatternFill(fill_type="solid", start_color='FFEEFFFF', end_color='FF001100')#边框可以选择的值为:'hair', 'medium', 'dashDot', 'dotted', 'mediumDashDot', 'dashed', 'mediumDashed', 'mediumDashDotDot', 'dashDotDot', 'slantDashDot', 'double', 'thick', 'thin']#diagonal 表示对角线bd = Border(left=Side(border_style="thin", color='FF001000'), right=Side(border_style="thin", color='FF110000'), top=Side(border_style="thin", color='FF110000'), bottom=Side(border_style="thin", color='FF110000'), diagonal=Side(border_style=None, color='FF000000'), diagonal_direction=0, outline=Side(border_style=None, color='FF000000'), vertical=Side(border_style=None, color='FF000000'), horizontal=Side(border_style=None, color='FF110000') )alignment=Alignment(horizontal='general', vertical='bottom', text_rotation=0, wrap_text=False, shrink_to_fit=False, indent=0)number_format = 'General'protection = Protection(locked=True, hidden=False)ws["B5"].font = ftws["B5"].fill =fillws["B5"].border = bdws["B5"].alignment = alignmentws["B5"].number_format = number_formatws["B5"].value ="zeke"# Save the filewb.save("e:\\sample.xlsx")
联系客服