xlwt是Python用来写Excel文件的包。

来源:互联网 发布:jquery post get json 编辑:程序博客网 时间:2024/05/21 17:49

xlwt是Python用来写Excel文件的包。

1. 最简单粗暴的写法:

[html] view plain copy
  1. f = xlwt.Workbook()  
  2. sheet1 = f.add_sheet(u'sheet1', cell_overwrite_ok=True)  
  3. sheet1.write(0,0,'some text')  
  4. f.save('test1.xls')  

这就可以了!

cell_overwrite_ok=True是为了可以让用户可以重复写内容用的。


2. 升级写法:加上字体风格

[html] view plain copy
  1. style = xlwt.XFStyle()  
  2. font = xlwt.Font()  
  3. font.name = 'Tahoma'  
  4. font.bold = True  
  5. font.italic = True  
  6. font.underline = True  
  7. style.font = font  
  8. sheet.write(0, 0, 'some bold Times text', style)  


3. 再提升一下Big:合并单元格

[html] view plain copy
  1. sheet1.write_merge(0,1,0,1,"sum")  

上面语句会合并A1:B2,并写入“sum”。

注意:write_merge的函数定义:

[html] view plain copy
  1. def write_merge(self, r1, r2, c1, c2, label=""style=Style.default_style):  

其中:
0 <= c1 <= c2 <= 255
0 <= r1 <= r2 <= 65535


4. Big还能再提升吗?可以!可以插入图片!

方法定义如下:

[html] view plain copy
  1. def insert_bitmap(self, filename, row, col, x = 0y = 0scale_x = 1scale_y = 1):