翼度科技»论坛 编程开发 python 查看内容

python: openpyxl操作Excel

7

主题

7

帖子

21

积分

新手上路

Rank: 1

积分
21
1、 安装
  1. pip install openpyxl
复制代码
  想要在文件中插入图片文件,需要安装pillow,安装文件:PIL-fork-1.1.7.win-amd64-py2.7.exe
  · font(字体类):字号、字体颜色、下划线等
  · fill(填充类):颜色等
  · border(边框类):设置单元格边框
  · alignment(位置类):对齐方式
  · number_format(格式类):数据格式
  · protection(保护类):写保护
2、创建一个excel 文件,并写入不同类的内容
  1. # -*- coding: utf-8 -*-
  2. from openpyxl import Workbook
  3. wb = Workbook()    #创建文件对象
  4. # grab the active worksheet
  5. ws = wb.active     #获取第一个sheet
  6. # Data can be assigned directly to cells
  7. ws['A1'] = 42      #写入数字
  8. ws['B1'] = "你好"+"automation test" #写入中文(unicode中文也可)
  9. # Rows can also be appended
  10. ws.append([1, 2, 3])    #写入多个单元格
  11. # Python types will automatically be converted
  12. import datetime
  13. import time
  14. ws['A2'] = datetime.datetime.now()    #写入一个当前时间
  15. #写入一个自定义的时间格式
  16. ws['A3'] =time.strftime("%Y年%m月%d日 %H时%M分%S秒",time.localtime())
  17. # Save the file
  18. wb.save("e:\\sample.xlsx")
复制代码
3、 创建sheet
  1. # -*- coding: utf-8 -*-
  2. from openpyxl import Workbook
  3. wb = Workbook()
  4. ws1 = wb.create_sheet("Mysheet")           #创建一个sheet
  5. ws1.title = "New Title"                    #设定一个sheet的名字
  6. ws2 = wb.create_sheet("Mysheet", 0)      #设定sheet的插入位置 默认插在后面
  7. ws2.title = u"你好"    #设定一个sheet的名字 必须是Unicode
  8. ws1.sheet_properties.tabColor = "1072BA"   #设定sheet的标签的背景颜色
  9. #获取某个sheet对象
  10. print wb.get_sheet_by_name(u"你好"  )
  11. print wb["New Title" ]
  12. #获取全部sheet 的名字,遍历sheet名字
  13. print wb.sheetnames
  14. for sheet_name in wb.sheetnames:
  15.     print sheet_name
  16. print "*"*50
  17. for sheet in wb:
  18.     print sheet.title
  19. #复制一个sheet
  20. wb["New Title" ]["A1"]="zeke"
  21. source = wb["New Title" ]
  22. target = wb.copy_worksheet(source)
  23. # w3 = wb.copy_worksheet(wb['new title'])
  24. # ws3.title = 'new2'
  25. # wb.copy_worksheet(wb['new title']).title = 'hello'
  26. # Save the file
  27. wb.save("e:\\sample.xlsx")
复制代码
4、 操作单元格
  1. # -*- coding: utf-8 -*-
  2. from openpyxl import Workbook
  3. wb = Workbook()
  4. ws1 = wb.create_sheet("Mysheet")           #创建一个sheet
  5. ws1["A1"]=123.11
  6. ws1["B2"]="你好"
  7. d = ws1.cell(row=4, column=2, value=10)
  8. print ws1["A1"].value
  9. print ws1["B2"].value
  10. print d.value
  11. # Save the file
  12. wb.save("e:\\sample.xlsx")
复制代码
5、 操作批量的单元格

无论ws.rows还是ws.iter_rows都是一个对象
除上述两个对象外 单行,单列都是一个元祖,多行多列是二维元祖
  1. # -*- coding: utf-8 -*-
  2. from openpyxl import Workbook
  3. wb = Workbook()
  4. ws1 = wb.create_sheet("Mysheet")           #创建一个sheet
  5. ws1["A1"]=1
  6. ws1["A2"]=2
  7. ws1["A3"]=3
  8. ws1["B1"]=4
  9. ws1["B2"]=5
  10. ws1["B3"]=6
  11. ws1["C1"]=7
  12. ws1["C2"]=8
  13. ws1["C3"]=9
  14. #操作单列
  15. print ws1["A"]
  16. for cell in ws1["A"]:
  17.     print cell.value
  18. #操作多列,获取每一个值
  19. print ws1["A:C"]
  20. for column in ws1["A:C"]:
  21.     for cell in column:
  22.         print cell.value
  23. #操作多行
  24. row_range = ws1[1:3]
  25. print row_range
  26. for row in row_range:
  27.     for cell in row:
  28.         print cell.value
  29. print "*"*50
  30. for row in ws1.iter_rows(min_row=1, min_col=1, max_col=3, max_row=3):
  31.     for cell in row:
  32.         print cell.value
  33. #获取所有行
  34. print ws1.rows
  35. for row in ws1.rows:
  36.     print row
  37. print "*"*50
  38. #获取所有列
  39. print ws1.columns
  40. for col in ws1.columns:
  41.     print col
  42. wb.save("e:\\sample.xlsx")
复制代码
使用百分数
  1. # -*- coding: utf-8 -*-
  2. from openpyxl import Workbook
  3. from openpyxl import load_workbook
  4. wb = load_workbook('e:\\sample.xlsx')
  5. wb.guess_types = True
  6. ws=wb.active
  7. ws["D1"]="12%"
  8. print ws["D1"].value
  9. # Save the file
  10. wb.save("e:\\sample.xlsx")
  11. #结果会打印小数
  12. # -*- coding: utf-8 -*-
  13. from openpyxl import Workbook
  14. from openpyxl import load_workbook
  15. wb = load_workbook('e:\\sample.xlsx')
  16. wb.guess_types = False
  17. ws=wb.active
  18. ws["D1"]="12%"
  19. print ws["D1"].value
  20. wb.save("e:\\sample.xlsx")
  21. #结果会打印百分数
复制代码
获取所有的行对象:
  1. #coding=utf-8
  2. from openpyxl import Workbook
  3. from openpyxl import load_workbook
  4. wb = load_workbook('e:\\sample.xlsx')
  5. ws=wb.active
  6. rows=[]
  7. for row in ws.iter_rows():
  8.             rows.append(row)
  9. print rows   #所有行
  10. print rows[0] #获取第一行
  11. print rows[0][0] #获取第一行第一列的单元格对象
  12. print rows[0][0].value #获取第一行第一列的单元格对象的值
  13. print rows[len(rows)-1] #获取最后行 print rows[-1]
  14. print rows[len(rows)-1][len(rows[0])-1] #获取第后一行和最后一列的单元格对象
  15. print rows[len(rows)-1][len(rows[0])-1].value #获取第后一行和最后一列的单元格对象的值
复制代码
获取所有的列对象:
  1. #coding=utf-8
  2. from openpyxl import Workbook
  3. from openpyxl import load_workbook
  4. wb = load_workbook('e:\\sample.xlsx')
  5. ws=wb.active
  6. cols=[]
  7. cols = []
  8. for col in ws.iter_cols():
  9.     cols.append(col)
  10. print cols   #所有列
  11. print cols[0]   #获取第一列
  12. print cols[0][0]   #获取第一列的第一行的单元格对象
  13. print cols[0][0].value   #获取第一列的第一行的值
  14. print "*"*30
  15. print cols[len(cols)-1]   #获取最后一列
  16. print cols[len(cols)-1][len(cols[0])-1]   #获取最后一列的最后一行的单元格对象
  17. print cols[len(cols)-1][len(cols[0])-1].value   #获取最后一列的最后一行的单元格对象的值
复制代码
6、 操作已经存在的文件
  1. # -*- coding: utf-8 -*-
  2. from openpyxl import Workbook
  3. from openpyxl import load_workbook
  4. wb = load_workbook('e:\\sample.xlsx')
  5. wb.guess_types = True   #猜测格式类型
  6. ws=wb.active
  7. ws["D1"]="12%"
  8. print ws["D1"].value
  9. # Save the file
  10. wb.save("e:\\sample.xlsx")
  11. #注意如果原文件有一些图片或者图标,则保存的时候可能会导致图片丢失
复制代码
7、 单元格类型
  1. # -*- coding: utf-8 -*-
  2. from openpyxl import Workbook
  3. from openpyxl import load_workbook
  4. import datetime
  5. wb = load_workbook('e:\\sample.xlsx')
  6. ws=wb.active
  7. wb.guess_types = True
  8. ws["A1"]=datetime.datetime(2010, 7, 21)
  9. print ws["A1"].number_format
  10. ws["A2"]="12%"
  11. print ws["A2"].number_format
  12. ws["A3"]= 1.1
  13. print ws["A4"].number_format
  14. ws["A4"]= "中国"
  15. print ws["A5"].number_format
  16. # Save the file
  17. wb.save("e:\\sample.xlsx")
  18. 执行结果:
  19. yyyy-mm-dd h:mm:ss
  20. 0%
  21. General
  22. General
  23. #如果是常规,显示general,如果是数字,显示'0.00_ ',如果是百分数显示0%
  24. 数字需要在Excel中设置数字类型,直接写入的数字是常规类型
复制代码
8、 使用公式
  1. # -*- coding: utf-8 -*-
  2. from openpyxl import Workbook
  3. from openpyxl import load_workbook
  4. wb = load_workbook('e:\\sample.xlsx')
  5. ws1=wb.active
  6. ws1["A1"]=1
  7. ws1["A2"]=2
  8. ws1["A3"]=3
  9. ws1["A4"] = "=SUM(1, 1)"
  10. ws1["A5"] = "=SUM(A1:A3)"
  11. print ws1["A4"].value  #打印的是公式内容,不是公式计算后的值,程序无法取到计算后的值
  12. print ws1["A5"].value  #打印的是公式内容,不是公式计算后的值,程序无法取到计算后的值
  13. # Save the file
  14. wb.save("e:\\sample.xlsx")
复制代码
9、 合并单元格
  1. # -*- coding: utf-8 -*-
  2. from openpyxl import Workbook
  3. from openpyxl import load_workbook
  4. wb = load_workbook('e:\\sample.xlsx')
  5. ws1=wb.active
  6. ws.merge_cells('A2:D2')
  7. ws.unmerge_cells('A2:D2')  #合并后的单元格,脚本单独执行拆分操作会报错,需要重新执行合并操作再拆分
  8. # or equivalently
  9. ws.merge_cells(start_row=2,start_column=1,end_row=2,end_column=4)
  10. ws.unmerge_cells(start_row=2,start_column=1,end_row=2,end_column=4)
  11. # Save the file
  12. wb.save("e:\\sample.xlsx")
复制代码
10、插入一个图片

需要先安装Pilow,安全文件是:PIL-fork-1.1.7.win-amd64-py2.7.exe
  1. # -*- coding: utf-8 -*-
  2. from openpyxl import load_workbook
  3. from openpyxl.drawing.image import Image
  4. wb = load_workbook('e:\\sample.xlsx')
  5. ws1=wb.active
  6. img = Image('e:\\1.png')
  7. ws1.add_image(img, 'A1')
  8. # Save the file
  9. wb.save("e:\\sample.xlsx")
复制代码
11、 隐藏单元格
  1. # -*- coding: utf-8 -*-
  2. from openpyxl import load_workbook
  3. from openpyxl.drawing.image import Image
  4. wb = load_workbook('e:\\sample.xlsx')
  5. ws1=wb.active
  6. ws1.column_dimensions.group('A', 'D', hidden=True)   #隐藏a到d列范围内的列
  7. #ws1.row_dimensions 无group方法
  8. # Save the file
  9. wb.save("e:\\sample.xlsx")
复制代码
12、 画一个柱状图
  1. # -*- coding: utf-8 -*-
  2. from openpyxl import load_workbook
  3. from openpyxl import Workbook
  4. from openpyxl.chart import BarChart, Reference, Series
  5. wb = load_workbook('e:\\sample.xlsx')
  6. ws1=wb.active
  7. wb = Workbook()
  8. ws = wb.active
  9. for i in range(10):
  10.     ws.append([i])
  11. values = Reference(ws, min_col=1, min_row=1, max_col=1, max_row=10)
  12. chart = BarChart()
  13. chart.add_data(values)
  14. ws.add_chart(chart, "E15")
  15. # Save the file
  16. wb.save("e:\\sample.xlsx")
复制代码
13、 画一个饼图
  1. # -*- coding: utf-8 -*-
  2. from openpyxl import load_workbook
  3. from openpyxl import Workbook
  4. from openpyxl.chart import (PieChart , ProjectedPieChart, Reference)
  5. from openpyxl.chart.series import DataPoint
  6. data = [
  7.     ['Pie', 'Sold'],
  8.     ['Apple', 50],
  9.     ['Cherry', 30],
  10.     ['Pumpkin', 10],
  11.     ['Chocolate', 40],
  12. ]
  13. wb = Workbook()
  14. ws = wb.active
  15. for row in data:
  16.     ws.append(row)
  17. pie = PieChart()
  18. labels = Reference(ws, min_col=1, min_row=2, max_row=5)
  19. data = Reference(ws, min_col=2, min_row=1, max_row=5)
  20. pie.add_data(data, titles_from_data=True)
  21. pie.set_categories(labels)
  22. pie.title = "Pies sold by category"
  23. # Cut the first slice out of the pie
  24. slice = DataPoint(idx=0, explosion=20)
  25. pie.series[0].data_points = [slice]
  26. ws.add_chart(pie, "D1")
  27. ws = wb.create_sheet(title="Projection")
  28. data = [
  29.     ['Page', 'Views'],
  30.     ['Search', 95],
  31.     ['Products', 4],
  32.     ['Offers', 0.5],
  33.     ['Sales', 0.5],
  34. ]
  35. for row in data:
  36.     ws.append(row)
  37. projected_pie = ProjectedPieChart()
  38. projected_pie.type = "pie"
  39. projected_pie.splitType = "val" # split by value
  40. labels = Reference(ws, min_col=1, min_row=2, max_row=5)
  41. data = Reference(ws, min_col=2, min_row=1, max_row=5)
  42. projected_pie.add_data(data, titles_from_data=True)
  43. projected_pie.set_categories(labels)
  44. ws.add_chart(projected_pie, "A10")
  45. from copy import deepcopy
  46. projected_bar = deepcopy(projected_pie)
  47. projected_bar.type = "bar"
  48. projected_bar.splitType = 'pos' # split by position
  49. ws.add_chart(projected_bar, "A27")
  50. # Save the file
  51. wb.save("e:\\sample.xlsx")
复制代码
14、 设定一个表格区域,并设定表格的格式
  1. # -*- coding: utf-8 -*-
  2. from openpyxl import load_workbook
  3. from openpyxl import Workbook
  4. from openpyxl.worksheet.table import Table, TableStyleInfo
  5. wb = Workbook()
  6. ws = wb.active
  7. data = [
  8.     ['Apples', 10000, 5000, 8000, 6000],
  9.     ['Pears',   2000, 3000, 4000, 5000],
  10.     ['Bananas', 6000, 6000, 6500, 6000],
  11.     ['Oranges',  500,  300,  200,  700],
  12. ]
  13. # add column headings. NB. these must be strings
  14. ws.append(["Fruit", "2011", "2012", "2013", "2014"])
  15. for row in data:
  16.     ws.append(row)
  17. tab = Table(displayName="Table1", ref="A1:E5")
  18. # Add a default style with striped rows and banded columns
  19. style = TableStyleInfo(name="TableStyleMedium9", showFirstColumn=True,
  20.                        showLastColumn=True, showRowStripes=True, showColumnStripes=True)
  21. #第一列是否和样式第一行颜色一行,第二列是否···
  22. #是否隔行换色,是否隔列换色
  23. tab.tableStyleInfo = style
  24. ws.add_table(tab)
  25. # Save the file
  26. wb.save("e:\\sample.xlsx")
复制代码
15、给单元格设定字体颜色
  1. # -*- coding: utf-8 -*-
  2. from openpyxl import Workbook
  3. from openpyxl.styles import colors
  4. from openpyxl.styles import Font
  5. wb = Workbook()
  6. ws = wb.active
  7. a1 = ws['A1']
  8. d4 = ws['D4']
  9. ft = Font(color=colors.RED)  # color="FFBB00",颜色编码也可以设定颜色
  10. a1.font = ft
  11. d4.font = ft
  12. # If you want to change the color of a Font, you need to reassign it::
  13. #italic 倾斜字体
  14. a1.font = Font(color=colors.RED, italic=True) # the change only affects A1
  15. a1.value = "abc"
  16. # Save the file
  17. wb.save("e:\\sample.xlsx")
复制代码
16、设定字体和大小
  1. # -*- coding: utf-8 -*-
  2. from openpyxl import Workbook
  3. from openpyxl.styles import colors
  4. from openpyxl.styles import Font
  5. wb = Workbook()
  6. ws = wb.active
  7. a1 = ws['A1']
  8. d4 = ws['D4']
  9. a1.value = "abc"
  10. from openpyxl.styles import Font
  11. from copy import copy
  12. ft1 = Font(name=u'宋体', size=14)
  13. ft2 = copy(ft1)   #复制字体对象
  14. ft2.name = "Tahoma"
  15. print ft1.name
  16. print ft2.name
  17. print ft2.size # copied from the
  18. a1.font = ft1
  19. # Save the file
  20. wb.save("e:\\sample.xlsx")
复制代码
17、设定行和列的字体
  1. # -*- coding: utf-8 -*-
  2. from openpyxl import Workbook
  3. from openpyxl.styles import Font
  4. wb = Workbook()
  5. ws = wb.active
  6. col = ws.column_dimensions['A']
  7. col.font = Font(bold=True)   #将A列设定为粗体
  8. row = ws.row_dimensions[1]
  9. row.font = Font(underline="single")  #将第一行设定为下划线格式
  10. # Save the file
  11. wb.save("e:\\sample.xlsx")
复制代码
18、设定单元格的边框、字体、颜色、大小和边框背景色
  1. # -*- coding: utf-8 -*-
  2. from openpyxl import Workbook
  3. from openpyxl.styles import Font
  4. from openpyxl.styles import NamedStyle, Font, Border, Side,PatternFill
  5. wb = Workbook()
  6. ws = wb.active
  7. highlight = NamedStyle(name="highlight")
  8. highlight.font = Font(bold=True, size=20,color= "ff0100")
  9. highlight.fill = PatternFill("solid", fgColor="DDDDDD")#背景填充
  10. bd = Side(style='thick', color="000000")
  11. highlight.border = Border(left=bd, top=bd, right=bd, bottom=bd)
  12. print dir(ws["A1"])
  13. ws["A1"].style =highlight
  14. # Save the file
  15. wb.save("e:\\sample.xlsx")
复制代码
19、常用的样式和属性设置
  1. # -*- coding: utf-8 -*-
  2. from openpyxl import Workbook
  3. from openpyxl.styles import Font
  4. from openpyxl.styles import NamedStyle, Font, Border, Side,PatternFill
  5. from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font
  6. wb = Workbook()
  7. ws = wb.active
  8. ft = Font(name=u'微软雅黑',
  9.     size=11,
  10.     bold=False,
  11.     italic=False,
  12.     vertAlign=None,
  13.     underline='none',
  14.     strike=False,
  15.     color='FF000000')
  16. fill = PatternFill(fill_type="solid",
  17.     start_color='FFEEFFFF',
  18.     end_color='FF001100')
  19. #边框可以选择的值为:'hair', 'medium', 'dashDot', 'dotted', 'mediumDashDot', 'dashed', 'mediumDashed', 'mediumDashDotDot', 'dashDotDot', 'slantDashDot', 'double', 'thick', 'thin']
  20. #diagonal 表示对角线
  21. bd = Border(left=Side(border_style="thin",
  22.               color='FF001000'),
  23.     right=Side(border_style="thin",
  24.                color='FF110000'),
  25.     top=Side(border_style="thin",
  26.              color='FF110000'),
  27.     bottom=Side(border_style="thin",
  28.                 color='FF110000'),
  29.     diagonal=Side(border_style=None,
  30.                   color='FF000000'),
  31.     diagonal_direction=0,
  32.     outline=Side(border_style=None,
  33.                  color='FF000000'),
  34.     vertical=Side(border_style=None,
  35.                   color='FF000000'),
  36.     horizontal=Side(border_style=None,
  37.                    color='FF110000')
  38.                 )
  39. alignment=Alignment(horizontal='general',
  40.         vertical='bottom',
  41.         text_rotation=0,
  42.         wrap_text=False,
  43.         shrink_to_fit=False,
  44.         indent=0)
  45. number_format = 'General'
  46. protection = Protection(locked=True,
  47.             hidden=False)
  48. ws["B5"].font = ft
  49. ws["B5"].fill =fill
  50. ws["B5"].border = bd
  51. ws["B5"].alignment = alignment
  52. ws["B5"].number_format = number_format
  53. ws["B5"].value ="zeke"
  54. # Save the file
  55. wb.save("e:\\sample.xlsx")
复制代码
来源:https://www.cnblogs.com/dancesir/p/17764443.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具