python

当前位置:首页 > openpyxl教程 > 当前文章

openpyxl教程

openpyxl修改sheet名,sheet颜色,删除sheet的方法

2020-04-04 148赞 python中国网
每篇文章努力于解决一个问题!python高级、python面试全套、操作系统经典课等可移步文章底部。

  万事万物的操作都是增删改查,sheet也不例外,前面我们讲了openpyxl查询和增加sheet的操作,本节课说下修改和删除的操作。

  1、修改sheet名字(通过sheet对象的title属性)

  You can change this name at any time with theWorksheet.title property:

	  ws.title = "New Title"

  2、修改sheet名背景颜色(通过sheet对象的sheet_properties.tabColor属性)

  The background color of the tab holding this title is white by default. You can change this providing anRRGGBBcolor code to theWorksheet.sheet_properties.tabColor attribute:

	  ws.sheet_properties.tabColor = "1072BA"

  3、删除sheet(通过remove方法)

  wb.remove(sheet) #参数为sheet对象而非sheet名

  1、修改sheet名代码如下:

# -*- coding: utf-8 -*-
from openpyxl import Workbook

wb = Workbook() # 默认生成一个名为Sheet的sheet

# 创建sheet
for name in ['a','b']:
    wb.create_sheet(name)

# 修改sheet名字
num = 1
for sheet in wb:
    name = sheet.title + str(num)
    sheet.title = name

# 获取sheet名
sheet_names = wb.sheetnames
print(sheet_names)

wb.save('test.xlsx')
D:python3installpython.exe D:/pyscript/py3script/python66/test2/test.py
['Sheet1', 'a1', 'b1']

Process finished with exit code 0


  2、修改sheet名文背景色代码如下

# -*- coding: utf-8 -*-
from openpyxl import Workbook

wb = Workbook() # 默认生成一个名为Sheet的sheet

# 创建sheet
for name in ['a','b']:
    ws = wb.create_sheet(name)

# 修改sheet名背景色
for sheet in wb:
    sheet.sheet_properties.tabColor = '1072BA'

wb.save('test.xlsx')

  3、删除sheet

# -*- coding: utf-8 -*-
from openpyxl import Workbook

wb = Workbook() # 默认生成一个名为Sheet的sheet

# 创建sheet
for name in ['a','b']:
    ws = wb.create_sheet(name)

# 删除sheet
ws = wb['a']
wb.remove(ws)

wb.save('test.xlsx')

文章评论

openpyxl修改sheet名,sheet颜色,删除sheet的方法文章写得不错,值得赞赏