xlwt模块的功能主要负责对Excel文件进行写入操作,xlwt官网将其描述为:xlwt is a library for writing data and formatting information to older Excel files (ie: .xls)【注意older】
注意:
该模块只可以将文件保存为xls格式的Excel文件,xls格式与xlms格式的区别简单来讲主要在于Excel对宏(VBA)的处理上
建议:
当使用Python在进行数据可视化处理时,将Python与Excel在数据可视化处理中各自应发挥的优势和功能做好定位和区分,减少试图通过Python来影响Excel内容或希望Python可以一键操作数据的要求,各自发挥各自的优势,这也是Python的精髓,Python官网将其描述为:Python is a programming language that lets you work quickly and integrate systems more effectively
官网地址:
https://xlwt.readthedocs.io/en/latest/
xlwt API:
https://xlwt.readthedocs.io/en/latest/api.html
- xlwt常用类有
1. Workbook类
《用于创建工作簿及操作内容的类,官方描述为:This is a class representing a workbook and all its contents. When creating Excel files with xlwt, you will normally start by instantiating an object of this class》
2. Worksheet类
《用于操作工作表内容的类,但该类不需要主动调用,主要由Workbook类中add_sheet方法返回,官方描述为:This is a class representing the contents of a sheet in a workbook. warning:You don't normally create instances of this class yourself. They are returned from calls to :meth:~xlwt.Workbook.Workbook.add_sheet
.》
3. Formatting类
《用于设置单元格样式具体包括6组,分别包括数字、对齐方式、边框、背景、保护,官方描述为:The XF record is able to store explicit cell formatting attributes or the attributes of a cell style. Explicit formatting includes the reference to a cell style XF record. This allows to extend a defined cell style with some explicit attributes. The formatting attributes are divided into 6 groups:
one group:Number format---Number format index (index to FORMAT record)
two group:Font---Font index (index to FONT record)
three group:Alignment---Horizontal and vertical alignment, text wrap, indentation, orientation/rotation, text direction
four group:Border---Border line styles and colours
five group:Background---Background area style and colours
six group:Protection---Cell locked, formula hidden》
4.Style类
《Style类为Formatting类提供了一个便捷操作的入口,通过调用Style类及Style类的函数可以间接实现对Formatting类操作,从而避免了Formatting类中庞杂的操作细节,Style类与Formatting类配置项相比多了num_format_str一项,该项用来指定自定义的数字格式》
- 部分源码如下
class XFStyle(object):
def __init__(self):
self.num_format_str = 'General'
self.font = Formatting.Font()
self.alignment = Formatting.Alignment()
self.borders = Formatting.Borders()
self.pattern = Formatting.Pattern()
self.protection = Formatting.Protection()
5.Column类
《该类用与设置工作表列的内容》
6.Row类
《该类用于设置工作表行的内容》
7. ExcelFormula类
《该类提供了Formula类函数,该函数用来满足工作表写入公式、超链接等其他特殊格式的数据》
-Workbook类常用方法
1. xlwt.Workbook(encoding='ascii', style_compression=0)
《建立一个新工作簿,encoding指定编码方式,compression指定是否压缩,该方法为类方法,即使用该方法时相当于建立了一个workbook实例》
2. xlwt.Workbook.Workbook.add_sheet(sheetname, cell_overwrite_ok=False)
《sheetname指定工作表名,overwrite为TRUE将不会弹出对同一工作表中同一单元格重写入的异常提示,该函数返回worksheet类》
- 部分源码如下
def add_sheet(self, sheetname, cell_overwrite_ok=False):
"""
This method is used to create Worksheets in a Workbook.
:param sheetname:
The name to use for this sheet, as it will appear in the
tabs at the bottom of the Excel application.
:param cell_overwrite_ok:
If ``True``, cells in the added worksheet will not raise an
exception if written to more than once.
:return:
The :class:`~xlwt.Worksheet.Worksheet` that was added.
"""
例:
newBook = xlwt.Workbook()
newSheet = newBook.add_sheet("FirstSheet",cell_overwrite_ok=False)
newSheet.write(0,0,"林州欢迎你")
newSheet.write(0,0,"林州欢迎你呀")
newBook.save("TheRedFlagCanyon2.xls")
输出错误提示:Exception: Attempt to overwrite cell: sheetname='FirstSheet' rowx=0 colx=0
3. xlwt.Workbook.Workbook.save(filename_or_stream)
《filename指定保存文件的名称或使用CompoundDoc类保存到IO流》
- 部分源码如下
def save(self, filename_or_stream):
"""
This method is used to save the Workbook to a file in native Excel
format.
:param filename_or_stream:
This can be a string containing a filename of
the file, in which case the excel file is saved to disk using the name
provided. It can also be a stream object with a write method, such as
a :class:`~io.StringIO`, in which case the data for the excel
file is written to the stream.
"""
例:
wb = xlwt.Workbook("utf-8",style_compression=0)
ws1 = wb.add_sheet("这是工作表1",cell_overwrite_ok=False)
ws2 = wb.add_sheet("这是工作表2",cell_overwrite_ok=False)
wb.save("test.xls")
- Worksheet类常用方法
1. xlwt.Worksheet.write(r, c, label="", style=Style.default_style)
《r表明要写入的单元格行数,默认从0开始,c表明要写入的单元格列数,默认从0开始,label指定数据转换的方式,如int型、long型将被转换为float型等,style指定由XFStyle类设置的样式》
- 部分源码如下
def write(self, r, c, label="", style=Style.default_style):
"""
This method is used to write a cell to a :class:`Worksheet`.
:param r:
The zero-relative number of the row in the worksheet to which
the cell should be written.
:param c:
The zero-relative number of the column in the worksheet to which
the cell should be written.
:param label:
The data value to be written.
An :class:`int`, :class:`long`, or
:class:`~decimal.Decimal` instance is converted to :class:`float`.
A :class:`unicode` instance is written as is. A :class:`bytes`
instance is converted to :class:`unicode` using the
encoding, which defaults to ``ascii``, specified when the
:class:`Workbook` instance was created.
A :class:`~datetime.datetime`, :class:`~datetime.date` or
:class:`~datetime.time` instance is converted into Excel date format
(a float representing the number of days since (typically)
``1899-12-31T00:00:00``, under the pretence that
1900 was a leap year).
A :class:`bool` instance will show up as ``TRUE`` or ``FALSE`` in
Excel.
``None`` causes the cell to be blank: no data, only formatting.
An :class:`xlwt.Formula` instance causes an Excel formula to be
written.
:param style:
A style, also known as an XF (extended format), is an
:class:`~xlwt.Style.XFStyle` object, which encapsulates the
formatting applied to the cell and its contents.
:class:`~xlwt.Style.XFStyle` objects are best set up using the
:func:`~xlwt.Style.easyxf` function. They may also be set up by
setting attributes in :class:`Alignment`, :class:`Borders`,
:class:`Pattern`, :class:`Font` and :class:`Protection` objects then
setting those objects and a format string as attributes of an
:class:`~xlwt.Style.XFStyle` object.
"""
2. xlwt.Worksheet.merge(r1, r2, c1, c2, style=Style.default_style)
《该函数用于合并参数指定的单元格,r1指定起始行,r2指定合并终止行,c1指定启始列,c2指定合并终止列,style指定合并样式》
例:
newBook = xlwt.Workbook()
newSheet = newBook.add_sheet("FirstSheet",cell_overwrite_ok=False)
newStyle = xlwt.Style.XFStyle()
alignement = xlwt.Alignment()
alignement.vert = 1
alignement.horz = 2
newStyle.alignment = alignement
newSheet.merge(0,1,0,3)
newSheet.write(0,0,"林州欢迎你",newStyle)
newSheet.write(0,4,"林州欢迎你呀")
newSheet.write(1,4,"林州还是欢迎你呀")
newSheet.write(2,0,"林州依然欢迎你呀")
newSheet.write(2,1,"林州还是欢迎你呀")
newSheet.write(2,2,"林州一直欢迎你呀")
newSheet.write(2,3,"林州总是欢迎你呀")
newSheet.write(2,4,"林州永远欢迎你呀")
newBook.save("TheRedFlagCanyon2.xls")
注意:当单元格合并后,数据填充的位置将变为起始行和起始列,且被合并的位置除起始行和起始列可填充外其余被合并的位置均不可写入数据
3. xlwt.Worksheet.write_merge(r1, r2, c1, c2, label="", style=Style.default_style)
《该函数同merge()函数除多出可指定写入数据外,其余完全相同》
例:
newBook = xlwt.Workbook()
newSheet = newBook.add_sheet("FirstSheet",cell_overwrite_ok=False)
newStyle = xlwt.Style.XFStyle()
alignement = xlwt.Alignment()
alignement.vert = 1
alignement.horz = 2
newStyle.alignment = alignement
#注意此处替换
newSheet.write_merge(0,1,0,3,"林州欢迎你",newStyle)
newSheet.write(0,4,"林州欢迎你呀")
newSheet.write(1,4,"林州还是欢迎你呀")
newSheet.write(2,0,"林州依然欢迎你呀")
newSheet.write(2,1,"林州还是欢迎你呀")
newSheet.write(2,2,"林州一直欢迎你呀")
newSheet.write(2,3,"林州总是欢迎你呀")
newSheet.write(2,4,"林州永远欢迎你呀")
newBook.save("TheRedFlagCanyon2.xls")
4.xlwt.Worksheet.insert_bitmap(filename, row, col, x = 0, y = 0, scale_x = 1, scale_y = 1)
《该函数用于插入参数指定的位图,filename指定要插入的位图文件名称,row,col指定插入的行和列,x,y指定距离,scale指定缩放比例,注意图片大小不能超过65K,且格式必须为bmp位图格式》
例:
newBook = xlwt.Workbook()
newSheet = newBook.add_sheet("FirstSheet",cell_overwrite_ok=False)
newStyle = xlwt.Style.XFStyle()
alignement = xlwt.Alignment()
alignement.vert = 1
alignement.horz = 2
newStyle.alignment = alignement
newSheet.write_merge(0,1,0,3,"林州欢迎你",newStyle)
newSheet.write(0,4,"林州欢迎你呀")
newSheet.write(1,4,"林州还是欢迎你呀")
newSheet.insert_bitmap('linzhou.bmp',2,0,x=10,y=10,scale_x=0.9,scale_y=0.9)
5.xlwt.Worksheet.get_name()
6.xlwt.Worksheet.set_name(value)
《函数5和函数6一个用来获取工作表的名称一个用来设置工作表的名称》
例:
newBook = xlwt.Workbook()
newSheet = newBook.add_sheet("FirstSheet",cell_overwrite_ok=False)
print(newSheet.get_name())
newSheet.set_name("WelcomeToLinzhou")
print(newSheet.get_name())
第一个输出:FirstSheet
第二个输出:WelcomeToLinzhou
7.xlwt.Worksheet.get_parent()
《该函数用来获取该工作表的父对象也就是工作簿》
例:
newBook = xlwt.Workbook()
newSheet = newBook.add_sheet("FirstSheet",cell_overwrite_ok=False)
newSheet2 = newSheet.get_parent().add_sheet("LinzhouWelcomeToyou",cell_overwrite_ok=True)
print(newSheet2.get_name())
第一个输出:LinzhouWelcomeToyou
8. xlwt.Worksheet.set_protect(value)
《为工作表设置文档保护,默认不保护,value接受一个数值型参数,非0表示保护该工作表》
9. xlwt.Worksheet.set_password(value)
《为工作表设置保护密码,当撤销工作表保护时需要输入该密码》
10.xlwt.Worksheet.set_panes_frozen(value)
10.1.xlwt.Worksheet.set_horz_split_pos(value)
10.2.xlwt.Wroksheet.set_vert_split_pos(value)
《函数10、10.1、10.2用来实现工作表的冻结功能,其中函数10指定开启工作表冻结功能,函数10.1指定要冻结的行,函数10.2指定要冻结的列》
例:
newBook = xlwt.Workbook()
newSheet1 = newBook.add_sheet("FirstSheet",cell_overwrite_ok=False)
newSheet2 = newBook.add_sheet("SecondSheet",cell_overwrite_ok=False)
#生成一个二维数组
z = [[a,b] for a in range(20) for b in range(20)]
#将二维数组中每一维的序号转换为字符串形式添加到每一维的数组中
[b.append(str(a)) for a, b in enumerate(z)]
#写入数据
for t in z:
newSheet1.write(t[0],t[1],t[2])
newSheet2.write(t[0],t[1],t[2])
#设置冻结对象
newSheet1.set_panes_frozen(1)
#设置冻结行
newSheet1.set_horz_split_pos(2)
#设置冻结列
newSheet1.set_vert_split_pos(2)
newBook.save("TheRedFlagCanyon3.xls")
11.xlwt.Wroksheet.set_show_headers(value)
《该函数用来隐藏工作表的行列标签,默认为显示》
例:
newSheet1.set_show_headers(0)
12.xlwt.Worksheet.set_show_grid(value)
《该函数用来隐藏网格线,默认为显示》
例:
newSheet1.set_show_grid(0)
13.xlwt.Worksheet.set_cols_right_to_left(value)
《该函数用来设置表格排列方式,默认为从左到右排序》
例:
newSheet1.set_cols_right_to_left(1)
14.xlwt.Worksheet.set_print_headers(value)
《设置打印行列标签,默认不打印》
例:
newSheet1.set_print_headers(1)
15.xlwt.Worksheet.set_print_grid(value)
《设置打印时候是否打印网格线,默认不打印》
例:
newSheet1.set_print_grid(1)
16.xlwt.Worksheet.set_print_centered_vert(value)
17.xlwt.Worksheet.set_print_centered_horz(value)
《函数16、17用来设置打印时是否居中显示,函数16指定是否垂直居中,默认不居中,函数17指定是否水平居中,默认居中》
例:
newSheet1.set_print_centered_vert(1)
newSheet1.set_print_centered_horz(1)
18.xlwt.Worksheet.set_header_str(value)
19.xlwt.Worksheet.set_footer_str(value)
《函数18、19用来设置工作表的页眉和页脚,其中函数18设置页眉,函数19设置页脚,注意由于Excel文件在使用时不显示页眉和页脚故只有在打印时页眉和页脚才有效,以上两个函数接受的特殊字符及代表的意义如下》
例:
newSheet1.set_header_str('NAME: &A DATE:&D No.&P'.encode())
newSheet1.set_footer_str('No.&P'.encode())
特殊字符意义如下:
&& The "&" character itself
&L Start of the left section
&C Start of the centred section
&R Start of the right section
&P Current page number
&N Page count
&D Current date
&T Current time
&A Sheet name (BIFF5-BIFF8)
&F File name without path
&Z File path without file name (BIFF8X)
&G Picture (BIFF8X)
&B Bold on/off (BIFF2-BIFF4)
&I Italic on/off (BIFF2-BIFF4)
&U Underlining on/off
&E Double underlining on/off (BIFF5-BIFF8)
&S Strikeout on/off
&X Superscript on/off (BIFF5-BIFF8)
&Y Subscript on/off (BIFF5-BIFF8)
20.xlwt.Worksheet.set_left_margin(value)
21.xlwt.Worksheet.set_right_margin(value)
22.xlwt.Worksheet.set_top_margin(value)
23.xlwt.Worksheet.set_bottom_margin(value)
24.xlwt.Worksheet.set_header_margin(value)
25.xlwt.Worksheet.set_footer_margin(value)
《函数20、21、22、23、24、25用来设置工作表的页边距,其中函数20指定设置左边距,默认0.3,函数21指定右边距,默认0.3,函数22指定上边距,默认0.6,函数23指定下边距,默认0.3,函数24指定页眉边距,默认0.1,函数25指定页脚边距,默认0.1》
例:
newSheet1.set_left_margin(0.5)
newSheet1.set_right_margin(0.5)
newSheet1.set_top_margin(0.5)
newSheet1.set_bottom_margin(0.5)
newSheet1.set_header_margin(0.5)
newSheet1.set_footer_margin(0.5)
newSheet1.set_header_str('No.&P'.encode())
newSheet1.set_footer_str('No.&P'.encode())
26.xlwt.Worksheet.set_paper_size_code(value)
27.xlwt.Worksheet.set_print_scaling(value)
28.xlwt.Worksheet.set_print_colour(value)
29.xlwt.Worksheet.set_vert_page_breaks(value)
30.xlwt.Worksheet.set_horz_page_breaks(value)
31.xlwt.Worksheet.set_print_notes(value)
32.xlwt.Worksheet.set_print_notes_at_end(value)
33.xlwt.Worksheet.set_print_omit_errors(value)
《函数26-33都是为设置Excel文件打印时的规格,其中函数26指定打印的纸张,其参数使用代号表示,代号如下图所示,函数27指定打印缩放比例,默认不缩放,函数28指定是否单色打印,默认为单色,函数29指定垂直打印区域,函数30指定水平打印区域,其中29、30函数不太明白,函数31设置是否打印批注,函数32设置是否将批注打印在文档结尾,函数33设置是否将错误单元格替换为#N/A打印,#N/A为默认打印,设置错误显示值如下图所示》
打印纸张代号编码
8 A3 297mm x 420mm
9 A4 210mm x 297mm
10 A4 small 210mm x 297mm
11 A5 148mm x 210mm
12 B4 (JIS) 257mm x 364mm
13 B5 (JIS) 182mm x 257mm
33 B4 (ISO) 250mm x 353mm
34 B5 (ISO) 176mm x 250mm
35 B6 (ISO) 125mm x 176mm
66 A2 420mm x 594mm
70 A6 105mm x 148mm
设置打印错误显示值
0 打印显示值
1 打印空白
2 打印 -
3 打印 #N/A
例:
newSheet1.set_paper_size_code(9) #A4纸
newSheet1.set_print_scaling(50) #缩小90%
newSheet1.set_print_colour(1) #单色打印
newSheet1.set_print_notes(1) #打印批注
newSheet1.set_print_notes_at_end(1) #末尾打印
newSheet1.set_print_omit_errors(3) #错误打印设置
34.xlwt.Worksheet.row(index)
35.xlwt.Worksheet.col(index)
《函数34用来定位工作表的行,函数35中col的全拼为column,意为定位工作表的列》
例:
newBook = xlwt.Workbook("utf-8",style_compression=False)
newSheet = newBook.add_sheet("FistSheet",cell_overwrite_ok=False)
newSheet.write(0,0,label="林州欢迎你")
newSheet.write(1,1,label="太行大峡谷欢迎你")
newSheet.write(2,2,label="红旗渠欢迎你")
newSheet.set_protect(1)
newSheet.set_password("this is unlock words")
newSheet.col(1).width = 4000
column = newSheet.row(1)
columnStyle = xlwt.Style.easyxf('font:height 400;')
column.set_style(columnStyle)
newBook.save("TheRedCanyon.xls")
36.xlwt.Worksheet.get_cols()
37.xlwt.Worksheet.get_rows()
《函数36用来获取当前工作表的列内容,格式为:xlwt.Column.Column object,函数37用来获取当前工作表的行内容,格式为xlwt.Row.Row object,但函数36计算方式不太明白,请慎用》
例:
print(instantiation.workSheet.get_cols())
print(instantiation.workSheet.get_rows())
第一个输出:{1: <xlwt.Column.Column object at 0x1071fead0>,......} 实有10列,但输出5列,且从1开始,搞不清为什么
第二个输出:{0: <xlwt.Row.Row object at 0x1071e6890>, ......},实有10行,输出10行,可以正确显示
- Formatting类包含的常用类有
1. Font类
《XFStyle类实际调用的设置字体类》
2. Alignment类
《XFStyle类实际调用的设置对齐类》
3. Borders类
《XFStyle类实际调用的设置边框类》
4.Pattern类
《XFStyle类实际调用的设置装饰类》
5. Protection类
《XFStyle类实际调用的设置保护类》
- Font类、Alignment类、Borders类、Pattern类、Protection类均可用_search_key函数来查询可设置的内容
- _search_key
《返回可设置的内容,每项均由字面意思表示》 - Font类_search_key源码如下
def _search_key(self):
return (
self.height, #度量值,指明字体大小,其为20的倍数,20为字体衡量单位
self.italic, #是否斜体,FALSEorTRUE
self.struck_out, #突出显示,指明是否设置删除线,FALSEorTRUE
self.outline, #是否设置轮廓,FALSEorTRUE
self.shadow, #是否设置阴影,FALSEorTRUE
self.colour_index, #颜色指示,指明字体颜色
self.bold, #是否加粗,FALSEorTRUE
self._weight, #
self.escapement, #
self.underline, #是否设置下划线,0(默认不带),1(单下划线),2(双下划线),3(会计用单下划线),4(会计用双下划线)
self.family, #指明字体家族
self.charset, #指明字符集
self.name, #指明字体名称
)
例:
newBook = xlwt.Workbook("utf-8",style_compression=False)
newSheet = newBook.add_sheet("FistSheet",cell_overwrite_ok=False)
reWriteXFStyle = xlwt.XFStyle()
reWriteFont = xlwt.Font()
reWriteFont.height = 400
reWriteFont.name = "微软雅黑"
reWriteFont.underline = True
reWriteFont.italic = True
reWriteXFStyle.font = reWriteFont
newSheet.write(0,0,"林州欢迎你",reWriteXFStyle)
newBook.save("TheRedCanyon.xls")
- Alignment类_search_key源码如下
def _search_key(self):
return (
self.horz, #horizontal,指明水平对齐方式,默认0(常规),1(左对齐),2(居中),3(右对齐),4(填充),5(两端对齐),6(跨列居中),7(分散对齐)
self.vert, #vertical,指明垂直对齐方式,默认2(低端对齐),0(顶端对齐),1(垂直居中),3(两端对齐),4(分散对齐)
self.dire, #direction,指明文字方向,默认0(根据内容),1(总是从左到右),2(总是从右到左)
self.orie, #orientation,指明定位,默认0
self.rota, #rotate,指明旋转方向,默认0,范围0-255
self.wrap, #是否设置自动换行,默认0(不自动换行),1(自动换行)
self.shri, #shrinkage,指明是否缩小字体填充,默认0(不缩小),1(缩小填充)
self.inde, #index,指明索引,默认0
self.merg, #merge,指明合并,默认0
)
例:
newBook = xlwt.Workbook("utf-8",style_compression=False)
newSheet = newBook.add_sheet("FistSheet",cell_overwrite_ok=False)
reWriteXFStyle = xlwt.XFStyle()
reWriteFont = xlwt.Font()
reWriteAlignment = xlwt.Alignment()
reWriteFont.height = 400
reWriteFont.name = "微软雅黑"
reWriteFont.underline = True
reWriteFont.italic = True
reWriteAlignment.horz = 2
reWriteAlignment.vert = 1
reWriteXFStyle.font = reWriteFont
reWriteXFStyle.alignment = reWriteAlignment
newSheet.write(0,0,"林州欢迎你",reWriteXFStyle)
newBook.save("TheRedCanyon.xls")
- Borders类_search_key源码如下
def _search_key(self):
return (
self.left, #左边框样式,默认0x00(不设置)
self.right, #右边框样式,默认0x00( 不设置)
self.top, #上边框样式,默认0x00(不设置)
self.bottom, #下边框样式,默认0x00(不设置)
self.diag, #diagonal,指明对角线样式,默认0x00(不设置)
self.left_colour, #左边框颜色,默认64
self.right_colour, #有边框颜色,默认64
self.top_colour, #上边框颜色,默认64
self.bottom_colour, #下边框颜色,默认64
self.diag_colour, #对角线颜色,默认64
self.need_diag1, #是否设置左上-右下对角线,默认0:NO_NEED_DIAG1(不显示),1:NEED_DIAG1(显示)
self.need_diag2, #是否设置左下-右上对角线,默认0:NO_NEED_DIAG2,1:NEED_DIAG2(显示)
)
例:
import xlwt
wb = xlwt.Workbook("utf-8",style_compression=0)
ws1 = wb.add_sheet("这是工作表1",cell_overwrite_ok=False)
cellStyle1 = xlwt.XFStyle()
cellStyle2 = xlwt.XFStyle()
cellStyleBorders1 = xlwt.Borders()
cellStyleBorders2 = xlwt.Borders()
cellStyleBorders1.left = 0x00
cellStyleBorders1.right = 0x01
cellStyleBorders1.top = 0x02
cellStyleBorders1.bottom = 0x03
cellStyleBorders1.left_colour = 0x10
cellStyleBorders1.right_colour = 0x11
cellStyleBorders1.top_colour = 0x12
cellStyleBorders1.bottom_colour = 0x13
cellStyleBorders1.need_diag1 = 1
cellStyleBorders1.diag = 0x13
cellStyleBorders1.diag_colour = 0x13
cellStyle1.borders = cellStyleBorders1
cellStyleBorders2.left = 0x04
cellStyleBorders2.right = 0x05
cellStyleBorders2.top = 0x06
cellStyleBorders2.bottom = 0x07
cellStyleBorders2.left_colour = 0x14
cellStyleBorders2.right_colour = 0x15
cellStyleBorders2.top_colour = 0x16
cellStyleBorders2.bottom_colour = 0x17
cellStyleBorders2.need_diag2 = 1
cellStyleBorders2.diag = 0x14
cellStyleBorders2.diag_colour = 0x14
cellStyle2.borders = cellStyleBorders2
ws1.write(0,0,"林州欢迎你",cellStyle1)
ws1.write(1,1,"林州欢迎你",cellStyle2)
wb.save("test.xls")
- Pattern类_search_key源码如下
def _search_key(self):
return (
self.pattern, #是否设置填充,默认0:NO_PATTERN(不设置),1:SOLID_PATTERN(纯色填充)
self.pattern_fore_colour, #设置填充的前景色,默认64
self.pattern_back_colour, #设置填充的背景色,默认65
)
例:
wb = xlwt.Workbook("utf-8",style_compression=0)
ws1 = wb.add_sheet("这是工作表1",cell_overwrite_ok=False)
cellStyle1 = xlwt.XFStyle()
cellStyle2 = xlwt.XFStyle()
cellStylePattern1 = xlwt.Pattern()
cellStylePattern1.pattern = 1
cellStylePattern1.pattern_back_colour = 0x0D
cellStylePattern1.pattern_fore_colour = 0x0D
cellStyle1.pattern = cellStylePattern1
cellStylePattern2 = xlwt.Pattern()
cellStylePattern2.pattern = 1
cellStylePattern2.pattern_back_colour = 0x0C
cellStylePattern2.pattern_fore_colour = 0x0C
cellStyle2.pattern = cellStylePattern2
ws1.write(0,0,"林州欢迎你",cellStyle1)
ws1.write(1,1,"林州欢迎你",cellStyle2)
wb.save("test.xls")
- Protection类_search_key源码如下
def _search_key(self):
return (
self.cell_locked, #设置单元格是否锁定,默认1(锁定),0(不锁定)
self.formula_hidden, #设置单元格公式是否隐藏,默认0(不隐藏),1(隐藏)
)
例:
newBook = xlwt.Workbook("utf-8",style_compression=False)
newSheet = newBook.add_sheet("FistSheet",cell_overwrite_ok=False)
newSheet.set_protect(256)
newSheet.set_password("this is unlock words")
reWriteXFStyle1 = xlwt.XFStyle()
reWriteXFStyle2 = xlwt.XFStyle()
reWriteProtect1 = xlwt.Protection()
reWriteProtect2 = xlwt.Protection()
reWriteProtect1.cell_locked = 0
reWriteProtect1.formula_hidden = 0
reWriteProtect2.formula_hidden = 1
reWriteXFStyle1.protection = reWriteProtect1
reWriteXFStyle2.protection = reWriteProtect2
newSheet.write(0,0,"下列单元格不可更改,且隐藏公式,注意,该标题不能更改")
newSheet.write(1,0,xlwt.Formula("-(1+1)"),reWriteXFStyle2)
newSheet.write(1,1,"下列单元格可以更改,不隐藏公式,注意,改标题不能更改")
newSheet.write(2,1,xlwt.Formula("(2+2)"),reWriteXFStyle1)
newBook.save("TheRedCanyon.xls")
- Style类常用函数
1. xlwt.Style.easyxf(***)
《用于便捷设置样式,该函数接受多个参数,但经常使用的为第一个参数和第二个参数,第一个参数将指定一个可读的设置样式字符串,第二个参数将指定数字的自定义格式》
- 部分源码如下
def easyxf(strg_to_parse="", num_format_str=None,
field_sep=",", line_sep=";", intro_sep=":", esc_char="\\", debug=False):
"""
This function is used to create and configure
:class:`XFStyle` objects for use with (for example) the
:meth:`Worksheet.write` method.
It takes a string to be parsed to obtain attribute values for
:class:`Alignment`, :class:`Borders`, :class:`Font`, :class:`Pattern` and
:class:`Protection` objects.
Refer to the examples in the file `examples/xlwt_easyxf_simple_demo.py`
and to the `xf_dict` dictionary in :mod:`xlwt.Style`.
Various synonyms including color/colour, center/centre and gray/grey are
allowed. Case is irrelevant (except maybe in font names). ``-`` may be used
instead of ``_``.
Example: ``font: bold on; align: wrap on, vert centre, horiz center``
:param num_format_str:
To get the "number format string" of an existing
cell whose format you want to reproduce, select the cell and click on
Format/Cells/Number/Custom. Otherwise, refer to Excel help.
Examples: ``"#,##0.00"``, ``"dd/mm/yyyy"``
:return: An :class:`XFstyle` object.
"""
例:
newBook = xlwt.Workbook("utf-8", style_compression=False)
newSheet = newBook.add_sheet("FistSheet", cell_overwrite_ok=False)
numberFormat = xlwt.Style.easyxf('',num_format_str='#,##0.00')
newSheet.write(0, 0, label="林州欢迎你")
newSheet.write(1, 1, label="太行大峡谷欢迎你")
newSheet.write(2, 2, label="红旗渠欢迎你")
newSheet.write(3, 3, 6811466,numberFormat)
column = newSheet.row(1)
columnStyle = xlwt.Style.easyxf('font: height 400,bold on;align: wrap on,vert center,horiz center;')
column.set_style(columnStyle)
newSheet.set_protect(1)
newSheet.set_password("this is unlock words")
newBook.save("TheRedCanyon.xls")
- ExcelFormula类常用函数
1. xlwt.ExcelFormula.Formula(object)
《该函数用来解析特殊的数据格式,如超链接、公式等,更多例子可在https://github.com/python-excel/xlwt/examples/formula.py查看》
例:
newBook = xlwt.Workbook("utf-8", style_compression=False)
newSheet = newBook.add_sheet("FistSheet", cell_overwrite_ok=False)
column = newSheet.row(1)
columnStyle = xlwt.Style.easyxf('font: height 400,bold on;align: wrap on,vert center,horiz center;')
column.set_style(columnStyle)
newSheet.write(0, 0, label="林州欢迎你")
newSheet.write(1, 1, xlwt.Formula("(444+222)"))
newSheet.write(2, 2, xlwt.Formula('HYPERLINK("http://www.linzhou.gov.cn/","林州政府")'))
newBook.save("TheRedCanyon.xls")