重新openpyxl.worksheet class:Worksheet里的append方法
最近在处理数据库数据并写入excel,使用的模块是openpyxl
Workbook Worksheet
Workbook:创建一个excel对象
Worksheet:创建excel的sheet
Worksheet里有个方法是append,这个很好,可以写入可迭代数据,就不用一个个单元格写入了
def append(self, iterable):
但是我有个需求:就是必须对excel字体格式处理,我再一行行遍历设置字体难免有点麻烦
看到源代码:
cell = Cell(self, row=row_idx, col_idx=col_idx, value=content)
我在源代码里面设置cell.font不就好了吗
于是改变源代码,新加了cell.font = Font(name=u"微软雅黑",size=10)
非常开心:代码生效了,保存生成的excel的字体按照我们预想的发生
后面又陷入了沉思:
总不能写了个工具,发布的时候把openpyxl模块 Worksheet.py也跟着发布吧,是不是很麻烦,也不能总py2exe打包成exe供别人使用。
于是灵光一现:代码重写Worksheet
重写的过程有点曲折,但最后经过一步步调试,还是被解决了。
得了个心得,验证了一句话:实践是检验真理的唯一标准
你去做了,就掌握了面向对象编程里的重写思想了,所以面向对象语言的受欢迎程度不言而喻
下面我们呈上重写代码:
from openpyxl.worksheet import Worksheet
class SubWorksheet(Worksheet):
def __init__(self,parent, title=None):
Worksheet.__init__(self,parent, title)
def append(self, iterable,font=None):
row_idx = self._current_row + 1
if (isinstance(iterable, (list, tuple, range))
or isgenerator(iterable)):
for col_idx, content in enumerate(iterable, 1):
if isinstance(content, Cell):
# compatible with write-only mode
cell = conten
cell.parent = self
cell.col_idx = col_idx
cell.row = row_idx
if font:
cell.font = font
else:
cell = Cell(self, row=row_idx, col_idx=col_idx, value=content)
if font:
cell.font = font
self._cells[(row_idx, col_idx)] = cell
elif isinstance(iterable, dict):
for col_idx, content in iteritems(iterable):
if isinstance(col_idx, basestring):
col_idx = column_index_from_string(col_idx)
cell = Cell(self, row=row_idx, col_idx=col_idx, value=content)
self._cells[(row_idx, col_idx)] = cell
else:
self._invalid_row(iterable)
self._current_row = row_idx
看到了什么区别了吗? def append(self, iterable,font=None): 方法里多了个对象font字体
def makeExcel(data,filename):
wb = Workbook()
from utils.subworksheet import SubWorksheet
ws = SubWorksheet(wb,title="Build_Data")
wb._add_sheet(ws, index=0)
for element in data:
ws.append(element,Font(name=u"微软雅黑",size=10))
wb.save(filename)
好了去检验下效果吧