Reference Link: http://bookshadow.com/weblog/2014/10/19/python-xlwt-write-excel/?utm_source=tuicool&utm_medium= Referral
Thanks to the author
Install package
If you need to use Python to write Excel files, first download or install XLWT.
If you have already installed Pip
install xlwt
Pip not installed
# git clone https://github.com/python-excel/xlwt.git# cd 解压目录# python setup.py install
Or not, download it here:
Download it ....
Create workbooks (workbook) and Worksheets (sheet):
import xlwtworkbook = xlwt.Workbook() sheet = workbook.add_sheet("Sheet Name"
Write cell (cell):
sheet.write(00‘foobar‘# row, column, value
Apply a style to a cell (bold for example):
style = xlwt.easyxf(‘font: bold 1‘)sheet.write(00‘foobar‘, style)
Set the column width:
To set the column width, you must set the Width property to 256*num_chars, where 256 equals 0 characters in width.
set width 256 = 1 width of 0 character
Apply multiple styles to a cell:
Note that each document style should be limited to 4k, which means that you should not initialize a style for each cell, but should reuse them (read the following to see a simple caching solution)
style = xlwt.easyxf(‘font: bold 1, color red;‘))sheet.write(00‘foobar‘, style)
Apply Currency Style:
To set the currency, add the keyword parameter num_format_str to the EASYXF function, or set the property in the returned Style object.
style = easyxf(num_format_str=‘$#,##0.00‘orsetonobjectstyle = easyxf(‘font: bold 1‘‘$#,##0.00‘sheet.write(00‘100.00‘, style)
Write Excel formula:
Use XLWT. Formula can be easily written in Excel formulas.
sheet.write(00, xlwt.Formula(‘HYPERLINK("http://yujitomita.com""click me")‘))
Save:
workbook.save("foobar.xls"# done!
Using Traps (gotchas):
Here are some common solutions for using traps.
Prohibit overwriting of cells:
tocreatewith kwarg cell_overwrite_okworkbook.add_sheet(‘foobar‘, cell_overwrite_ok=True
Valid worksheets are named:
The sheet name must be less than 31 characters
The name should not contain special characters, such as ': ', '/' etc.
4k style limits per document:
If you know the rules, applying a cell style is a piece of cake.
A cache easyxf function was created that first attempts to pull an existing style from the cache before creating a new style.
class MyClass(object): kwd_mark = object() def cached_easyxf(self, string=‘‘, **kwargs): ifnot‘_cached_easyxf‘): self._cached_easyxf = {} key = (string,) + (self.kwd_mark,) + tuple(sorted(kwargs.items())) return self._cached_easyxf.setdefault(key, xlwt.easyxf(string, **kwargs))
EASYXF string Format:
。
Receives a space-delimited array of key values for the string format.
‘KEYKEYKEYKEY-VALUE2 VALUE2′sheet.write(00, xlwt.easyxf(‘font: bold 1‘)) # boldsheet.write(00, xlwt.easyxf(‘font: bold 1, color: blue, underline single‘))
Have not finished learning, good sleepy, sleep ...
Not to be continued
Daydayup_python Self-study tutorial [14]_python operation Excel