• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python使用openpyxl库修改excel表格数据方法

python 搞代码 4年前 (2022-01-09) 13次浏览 已收录 0个评论

这篇文章主要介绍了关于使用python使用openpyxl库修改excel表格数据方法,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

1、openpyxl库可以读写xlsx格式的文件,对于xls旧格式的文件只能用xlrd读,xlwt写来完成了。

简单封装类:

from openpyxl import load_workbookfrom openpyxl import Workbookfrom openpyxl.chart import BarChart, Series, Reference, BarChart3Dfrom openpyxl.styles import Color, Font, Alignmentfrom openpyxl.styles.colors import BLUE, RED, GREEN, YELLOWclass Write_excel(object):  def __init__(self,filename):    self.filename = filename    self.wb = load_workbook(self.filename)    self.ws = self.wb.active  def write(self, coord, value):    # eg: coord:A1    self.ws.cell(coord).value = value    self.wb.save(self.filename)  def merge(self, rangstring):    # eg: rangstring:A1:E1    self.ws.merge_cells(rangstring)    self.wb.save(self.filename)  def cellstyle(self, coord, font, align):    cell = self.ws.cell(coord)    cell.font = font    cell.alignment = align  def makechart(self, title, pos, width, height, col1, row1, col2, row2, col3, row3, row4):    ''':param title:图表名         pos:图表位置         width:图表宽度         height:图表高度    '''    data = Reference(self.ws, min_col=col1, min_row=row1, max_col=col2, max_row=row2)    cat = Reference(<span>本文来源gaodai#ma#com搞*!代#%^码$网*</span>self.ws, min_col=col3, min_row=row3, max_row=row4)    chart = BarChart3D()    chart.title = title    chart.width = width    chart.height = height    chart.add_data(data=data, titles_from_data=True)    chart.set_categories(cat)    self.ws.add_chart(chart, pos)    self.wb.save(self.filename)

简单使用:

1、新建excel文件处理

wb = Workbook()#创建工作簿 ws = wb.active#激活工作表 ws1 = wb.create_sheet("Mysheet")#创建mysheet表 ws.title = "New Title"#表明改为New Title ws.sheet_properties.tabColor = "1072BA"#颜色 ws['A4'] = 4#赋值 d = ws.cell(row=4, column=2, value=10)#赋值 cell_range = ws['A1':'C2']#选择单元格区域 wb.save('test.xlsx')#保存

2、已有excel文件的处理

a、修改excel数据

wr = Write_excel('d:\demo.xlsx') wr.write('A2','hello')

b、合并单元格

wr.merge('A1:B3')

c、单元格加入样式,如字体,颜色等属性

单元格B2设置宋体,14号,红色,自动换行,水平居中,垂直居中

font = Font(name=u'宋体', size=14, color=RED, bold=True)align = Alignment(horizontal='center', vertical='center')wr.cellstyle('B2', font, align)

d、创建3d柱状图

rows = [   (None, 2013, 2014),   ("Apples", 5, 4),   ("Oranges", 6, 2),   ("Pears", 8, 3) ]  for row in rows:   ws.append(row)  wr.makechart(u"3D Bar Chart", 'E5', 12.5, 7, 2, 1, 3, 4, 1, 2, 4)

可以创建3d柱状和折线图表,挺好用的。

相关推荐:

Python使用matplotlib实现的图像读取、切割裁剪功能示例

Python使用email模块对邮件进行编码和解码

以上就是python使用openpyxl库修改excel表格数据方法的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python使用openpyxl库修改excel表格数据方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址