1、python 模块介绍- xlwt 创建 xls 文件(excel)2013-06-24 磁针石转自: http:/ xlwt 实例 .131.1.1 创建简单的 excel 文件 .131.1.2 插入图片 .2使用 insert_bitmap 来插入图片。 .331.1.3 设置样式 .331.1.4 更多实例 .4输出了红色的”Test”,并在第 3 行包含了公式: .4这里另有一个公式的实例: .5日期格式的实例 .6下面展示了不同边框和删除样式的字体: .7下面展示了不同颜色的字体,可以作为颜色参考: .7通过 unicode 输出字符 .9冻结: .10更多的公式: .12保护实例
2、: .1331.1.5 完整实例 .1631.1 xlwt 实例31.1.1 创建简单的 excel 文件下面例子,创建一个名为 mini.xls 的文件,它有一个空 sheet:xlwt was here 。from xlwt import *w = Workbook()ws = w.add_sheet(xlwt was here)w.save(mini.xls)Workbook 类初始化时有 encoding 和 style_compression 参数。encoding,设置字符编码,一般要这样设置:w = Workbook(encoding=utf-8),就可以在excel 中输出中文
3、了。默认是 ascii。当然要记得在文件头部添加:#!/usr/bin/env python# -*- coding: utf-8 -*-style_compression 表示是否压缩,不常用。Workbook 还有一些属性:Owner 设置文档所有者。country_code:国家码wnd_protect:窗口保护obj_protect:对象保护Protect:保护backup_on_save:保存时备份Hpos:横坐标Vpos:纵坐标Width:宽度Height:高度active_sheet:活动 sheettab_width:tab 宽度wnd_visible:窗口是否可见wnd_mi
4、ni:窗口最小化hscroll_visible:横向滚动条是否可见。vscroll_visible:纵向滚动条是否可见。tabs_visible:tab 是否可见。dates_1904:是否使用 1904 日期系统use_cell_values:单元格的值default_style:默认样式colour_RGB:颜色比如设置国家码:From xlwt import *w= Workbook()w.country_code= 61ws= w.add_sheet(AU)w.save(country.xls)方法有:add_style,add_font,add_str,del_str ,str_in
5、dex,add_rt, rt_index,add_sheet ,get_sheet,raise_bad_sheetname,convert_sheetindex,setup_xcall,add_sheet_reference。31.1.2 插入图片add_sheet 会返回一个 Worksheet 类。创建的时候有可选参数 cell_overwrite_ok,表示是否可以覆盖单元格,其实是 Worksheet 实例化的一个参数,默认值是 False。Worksheet 初始化的参数有: sheetname,parent_book,cell_overwrite_ok。Worksheet 的属性有
6、:Row , Column,explicit_magn_setting(默认 False),visibility(默认 0),split_position_units_are_twips(默认 False),row_default_height_mismatch,row_default_hidden,row_default_space_above ,row_default_space_below,last_used_row , first_used_row,last_used_col,row_tempfile。以上属性类定义中。函数构成的属性有:name,parent (只读),rows(只读
7、),cols(只读),merged_ranges(只读),bmp_rec(只读),show_formulas,show_grid, show_headers,panes_frozen,auto_colour_grid,cols_right_to_left, show_outline,remove_splits,selected ,sheet_visible,page_preview,first_visible_row,first_visible_col,grid_colour,preview_magn,normal_magn ,scl_magn ,vert_split_pos ,horz_sp
8、lit_pos,vert_split_first_visible,horz_split_first_visible,show_auto_page_breaks ,dialogue_sheet,auto_style_outline,outline_below,outline_right,fit_num_pages,show_row_outline,show_col_outline,alt_expr_eval,alt_formula_entries,row_default_height ,col_default_width,calc_mode ,calc_count,RC_ref_mode,ite
9、rations_on,delta,save_recalc,print_headers,print_grid,vert_page_breaks,horz_page_breaks, header_str,footer_str,print_centered_vert,print_centered_horz,left_margin,right_margin, top_margin,bottom_margin ,paper_size_code,print_scaling,start_page_number ,fit_width_to_pages ,fit_height_to_pages ,print_i
10、n_rows,portrait,print_colour,print_draft,print_notes,print_notes_at_end,print_omit_errors,print_hres,print_vres,header_margin,footer_margin,copies_num,wnd_protect,obj_protect,protect,scen_protect,password。方法有:get_parent,write,write_rich_text ,merge,write_merge,insert_bitmap,col,row,row_height,col_wi
11、dth。使用 insert_bitmap 来插入图片。from xlwt import *,w = Workbook()ws = w.add_sheet(Image)ws.insert_bitmap(python.bmp, 2, 2)ws.insert_bitmap(python.bmp, 10, 2)w.save(image.xls)31.1.3 设置样式改变字体的高度:#!/usr/bin/envpython#-*- coding: utf-8 -*-#Copyright (C) 2005 Kiseliov Romanfromxlwt import *w= Workbook(encodin
12、g=utf-8)ws= w.add_sheet(Hey, Dude)fori in range(6, 80):fnt = Font()fnt.height = i*20style = XFStyle()style.font = fntws.write(i, 1, 武冈)ws.row(i).set_style(style)w.save(row_styles.xls)XFStyle 用于设置字体样式,有描述字符串 num_format_str,字体 font,居中alignment,边界 borders,模式 pattern,保护 protection 等属性。另外还可以不写单元格,直接设置格式,
13、比如:from pyExcelerator import *w= Workbook()ws= w.add_sheet(Hey, Dude)fori in range(6, 80):fnt = Font()fnt.height = i*20style = XFStyle()style.font = fntws.row(i).set_style(style)w.save(row_styles_empty.xls)设置列宽:ws.col(i).width = 0x0d00 + i31.1.4 更多实例输出了红色的”Test”,并在第 3 行包含了公式:importxlwtfromdatetime i
14、mport datetimefont0= xlwt.Font()font0.name= Times New Romanfont0.colour_index= 2font0.bold= Truestyle0= xlwt.XFStyle()style0.font= font0style1= xlwt.XFStyle()style1.num_format_str= D-MMM-YYwb= xlwt.Workbook()ws= wb.add_sheet(A Test Sheet)ws.write(0,0, Test, style0)ws.write(1,0, datetime.now(), style
15、1)ws.write(2,0, 1)ws.write(2,1, 1)ws.write(2,2, xlwt.Formula(“A3+B3“)wb.save(example.xls)这里另有一个公式的实例:fromxlwt import ExcelFormulaParser, ExcelFormulaimportsysf= ExcelFormula.Formula(“-(1.80 + 2.898 * 1)/(1.80 + 2.898)*AVERAGE(1.80+ 2.898 * 1)/(1.80 + 2.898); (1.80 + 2.898 * 1)/(1.80 + 2.898); (1.80
16、+ 2.898 * 1)/(1.80 + 2.898) + SIN(PI()/4)“)合并单元格的实例注意 write_merge,1,2 个参数表示行数, 3,4 的参数表示列数。fromxlwt import *wb= Workbook()ws0= wb.add_sheet(sheet0)fnt= Font()fnt.name= Arialfnt.colour_index= 4fnt.bold= Trueborders= Borders()borders.left= 6borders.right= 6borders.top= 6borders.bottom= 6style= XFStyle
17、()style.font= fntstyle.borders = bordersws0.write_merge(3,3, 1, 5, test1, style)ws0.write_merge(4,10, 1, 5, test2, style)ws0.col(1).width= 0x0d00wb.save(merged0.xls)日期格式的实例fromxlwt import *fromdatetime import datetimew= Workbook()ws= w.add_sheet(Hey, Dude)fmts= M/D/YY,D-MMM-YY,D-MMM,MMM-YY,h:mm AM/P
18、M,h:mm:ss AM/PM,h:mm,h:mm:ss,M/D/YY h:mm,mm:ss,h:mm:ss,mm:ss.0,i= 0forfmt in fmts:ws.write(i, 0, fmt)style = XFStyle()style.num_format_str = fmtws.write(i, 4, datetime.now(), style)i += 1w.save(dates.xls)下面展示了不同边框和删除样式的字体:fromxlwt import *font0= Font()font0.name= Times New Romanfont0.struck_out= Tru
19、efont0.bold= Truestyle0= XFStyle()style0.font= font0wb= Workbook()ws0= wb.add_sheet(0)ws0.write(1,1, Test, style0)fori in range(0, 0x53):borders = Borders()borders.left = iborders.right = iborders.top = iborders.bottom = istyle = XFStyle()style.borders = bordersws0.write(i, 2, , style)ws0.write(i, 3
20、, hex(i), style0)ws0.write_merge(5,8, 6, 10, “)wb.save(blanks.xls)下面展示了不同颜色的字体,可以作为颜色参考:from xlwt import *font0 = Font()font0.name = Times New Romanfont0.struck_out = Truefont0.bold = Truestyle0 = XFStyle()style0.font = font0wb = Workbook()ws0 = wb.add_sheet(0)ws0.write(1, 1, Test, style0)for i in r
21、ange(0, 0x53):fnt = Font()fnt.name = Arialfnt.colour_index = ifnt.outline = Trueborders = Borders()borders.left = istyle = XFStyle()style.font = fntstyle.borders =bordersws0.write(i, 2,colour, style)ws0.write(i, 3,hex(i), style0)wb.save(format.xls)超级链接的插入方法:fromxlwt import *f= Font()f.height= 20*72f
22、.name= Verdanaf.bold= Truef.underline= Font.UNDERLINE_DOUBLEf.colour_index= 4h_style= XFStyle()h_style.font= fw= Workbook()ws= w.add_sheet(F)#NOTE: parameters are separated by semicolon!#n= “HYPERLINK“ws.write_merge(1,1, 1, 10, Formula(n +(“http:/www.irs.gov/pub/irs-pdf/f1000.pdf“;“f1000.pdf“),h_sty
23、le)ws.write_merge(2,2, 2, 25, Formula(n +(“mailto:?subject=pyExcelerator-feedback“pyExcelerator-feedback“),h_style)w.save(“hyperlinks.xls“)通过 unicode 输出字符在没有指定编码的情况下,也可以通过 unicode 输出字符,不过这样比较费劲,建议还是使用 utf-8 编码:fromxlwt import *w= Workbook()ws1= w.add_sheet(uNGREEK SMALL LETTER ALPHANGREEK SMALL LETT
24、ER BETANGREEKSMALL LETTER GAMMA)ws1.write(0,0, uNGREEK SMALL LETTER ALPHANGREEK SMALL LETTER BETANGREEK SMALLLETTER GAMMA)ws1.write(1,1, uNGREEK SMALL LETTER DELTAx = 1 + NGREEK SMALL LETTER DELTA)ws1.write(2,0,uAu2262u0391.) # RFC2152 examplews1.write(3,0,uHi Mom -u263a-!) # RFC2152 examplews1.writ
25、e(4,0,uu65E5u672Cu8A9E) # RFC2152 examplews1.write(5,0,uItem 3 is u00a31.) # RFC2152 examplews1.write(8,0,uNINTEGRAL) # RFC2152 examplew.add_sheet(uAu2262u0391.) # RFC2152 examplew.add_sheet(uHiMom -u263a-!) # RFC2152 exampleone_more_ws= w.add_sheet(uu65E5u672Cu8A9E) # RFC2152 examplew.add_sheet(uIt
26、em3 is u00a31.) # RFC2152 exampleone_more_ws.write(0,0, uu2665u2665)w.add_sheet(uNGREEKSMALL LETTER ETA WITH TONOS)w.save(unicode1.xls)冻结:fromxlwt import *w= Workbook()ws1= w.add_sheet(sheet 1)ws2= w.add_sheet(sheet 2)ws3= w.add_sheet(sheet 3)ws4= w.add_sheet(sheet 4)ws5= w.add_sheet(sheet 5)ws6= w.
27、add_sheet(sheet 6)fori in range(0x100):ws1.write(i/0x10, i%0x10, i)fori in range(0x100):ws2.write(i/0x10, i%0x10, i)fori in range(0x100):ws3.write(i/0x10, i%0x10, i)fori in range(0x100):ws4.write(i/0x10, i%0x10, i)fori in range(0x100):ws5.write(i/0x10, i%0x10, i)fori in range(0x100):ws6.write(i/0x10, i%0x10, i)