xls4-想要使用Python的xlwt设置单元格的背景色。

但是不知道如何设置。

【解决过程】

1.从Working with Excel Files in Python 找到官网的:The xlwt Module,无果。

2.参考:

XLWT : Changing the Cell Background Color

试了其代码:


1

2

3

4

5

6

7

8

9

10

badBG = xlwt.Pattern()

badBG.SOLID_PATTERN = 0x34

badBG.NO_PATTERN = 0x34

badBG.pattern_fore_colour = 0x34

badBG.pattern_back_colour = 0x34

badFontStyle = xlwt.XFStyle()

badFontStyle.Pattern = badBG

sheet1.write(1,1,‘hello world‘, badFontStyle)

未果。

不过后来才知道,下面的代码:


1

2

3

4

5

6

badBG = xlwt.Pattern()

badBG.pattern = badBG.SOLID_PATTERN

badBG.pattern_fore_colour = 3

badFontStyle = xlwt.XFStyle()

badFontStyle.pattern = badBG

是可以设置背景色的。

但是很有限制。

而且对应的3是Green的意思,也是后来才知道的。

3.后来

是从

python xlwt set custom background colour of a cell

中,试了试其所用的代码:


1

style1 = xlwt.easyxf(‘pattern: pattern solid, fore_colour red;‘)

最终,经过测试,改为自己所需的代码的:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

import xlwt;

    #styleBlueBkg = xlwt.easyxf(‘font: color-index red, bold on‘);

    #styleBlueBkg = xlwt.easyxf(‘font: background-color-index red, bold on‘);

    #styleBlueBkg = xlwt.easyxf(‘pattern: pattern solid, fore_colour red;‘);

    #styleBlueBkg = xlwt.easyxf(‘pattern: pattern solid, fore_colour blue;‘);

    #styleBlueBkg = xlwt.easyxf(‘pattern: pattern solid, fore_colour light_blue;‘);

    #styleBlueBkg = xlwt.easyxf(‘pattern: pattern solid, fore_colour pale_blue;‘);

    #styleBlueBkg = xlwt.easyxf(‘pattern: pattern solid, fore_colour dark_blue;‘);

    #styleBlueBkg = xlwt.easyxf(‘pattern: pattern solid, fore_colour dark_blue_ega;‘);

    #styleBlueBkg = xlwt.easyxf(‘pattern: pattern solid, fore_colour ice_blue;‘);

    styleBlueBkg = xlwt.easyxf(‘pattern: pattern solid, fore_colour ocean_blue; font: bold on;‘); # 80% like

    #styleBlueBkg = xlwt.easyxf(‘pattern: pattern solid, fore_colour sky_blue;‘);

    

    

    #blueBkgFontStyle = xlwt.XFStyle()

    #blueBkgFontStyle.Pattern = blueBackgroundPattern;

    #styleBlueBkg = blueBkgFontStyle;

    

    styleBold   = xlwt.easyxf(‘font: bold on‘);

    

    wb = xlwt.Workbook();

    ws = wb.add_sheet(‘realPropertyInfo‘);

    

    ws.write(00"Sequence",  styleBlueBkg);

    ws.write(01"MapID",     styleBlueBkg);

    ws.write(02"Owner1",    styleBold);

    ws.write(03"Owner2",    styleBold);

    

    wb.save(excelFilename);

对应的,上述颜色的选择,可以参考这里:

https://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/Style.py

摘录如下:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

# Text values for colour indices. "grey" is a synonym of "gray".

# The names are those given by Microsoft Excel 2003 to the colours

# in the default palette. There is no great correspondence with

# any W3C name-to-RGB mapping.

_colour_map_text = """\

aqua 0x31

black 0x08

blue 0x0C

blue_gray 0x36

bright_green 0x0B

brown 0x3C

coral 0x1D

cyan_ega 0x0F

dark_blue 0x12

dark_blue_ega 0x12

dark_green 0x3A

dark_green_ega 0x11

dark_purple 0x1C

dark_red 0x10

dark_red_ega 0x10

dark_teal 0x38

dark_yellow 0x13

gold 0x33

gray_ega 0x17

gray25 0x16

gray40 0x37

gray50 0x17

gray80 0x3F

green 0x11

ice_blue 0x1F

indigo 0x3E

ivory 0x1A

lavender 0x2E

light_blue 0x30

light_green 0x2A

light_orange 0x34

light_turquoise 0x29

light_yellow 0x2B

lime 0x32

magenta_ega 0x0E

ocean_blue 0x1E

olive_ega 0x13

olive_green 0x3B

orange 0x35

pale_blue 0x2C

periwinkle 0x18

pink 0x0E

plum 0x3D

purple_ega 0x14

red 0x0A

rose 0x2D

sea_green 0x39

silver_ega 0x16

sky_blue 0x28

tan 0x2F

teal 0x15

teal_ega 0x15

turquoise 0x0F

violet 0x14

white 0x09

yellow 0x0D"""

4.后来才发现,其实,上述的方法,就是前面在

Setting the Background Color of a Cell

所介绍的内容:


1

2

3

4

5

6

7

8

9

10

import xlwt

workbook = xlwt.Workbook()

worksheet = workbook.add_sheet(‘My Sheet‘)

pattern = xlwt.Pattern() # Create the Pattern

pattern.pattern = xlwt.Pattern.SOLID_PATTERN # May be: NO_PATTERN, SOLID_PATTERN, or 0x00 through 0x12

pattern.pattern_fore_colour = 5 # May be: 8 through 63. 0 = Black, 1 = White, 2 = Red, 3 = Green, 4 = Blue, 5 = Yellow, 6 = Magenta, 7 = Cyan, 16 = Maroon, 17 = Dark Green, 18 = Dark Blue, 19 = Dark Yellow , almost brown), 20 = Dark Magenta, 21 = Teal, 22 = Light Gray, 23 = Dark Gray, the list goes on...

style = xlwt.XFStyle() # Create the Pattern

style.pattern = pattern # Add Pattern to Style

worksheet.write(00‘Cell Contents‘, style)

workbook.save(‘Excel_Workbook.xls‘)

只是当时觉得太繁琐,没有自己看而已。

【总结】

如上代码所示:

  • 可以通过xlwt.Pattern()然后得到pattern,设置pattern_fore_colour即可,但是颜色选择很有限。
  • 也可以通过更方便的:
    • xlwt.easyxf(‘pattern: pattern solid, fore_colour ocean_blue; font: bold on;’);
    • 去设置背景色。

python xlwt写excel格式控制 颜色、模式、编码、背景色

关于写excel的格式控制,比如颜色等等

 1 import xlwt
 2 from datetime import datetime
 3
 4 font0 = xlwt.Font()
 5 font0.name = ‘Times New Roman‘
 6 font0.colour_index = 2
 7 font0.bold = True
 8
 9 style0 = xlwt.XFStyle()
10 style0.font = font0
11
12 style1 = xlwt.XFStyle()
13 style1.num_format_str = ‘D-MMM-YY‘
14
15 wb = xlwt.Workbook()
16 ws = wb.add_sheet(‘A Test Sheet‘)
17
18 ws.write(0, 0, ‘Test‘, style0)
19 ws.write(1, 0, datetime.now(), style1)
20 ws.write(2, 0, 1)
21 ws.write(2, 1, 1)
22 ws.write(2, 2, xlwt.Formula("A3+B3"))
23
24 wb.save(‘example.xls‘)

Examples Generating Excel Documents Using Python’s xlwt

Here are some simple examples using Python’s xlwt library to dynamically generate Excel documents.

Please note a useful alternative may be ezodf, which allows you to generate ODS (Open Document Spreadsheet) files for LibreOffice / OpenOffice. You can check them out at:http://packages.python.org/ezodf/index.html

The Simplest Example
import xlwt
workbook = xlwt.Workbook(encoding = ‘ascii‘)
worksheet = workbook.add_sheet(‘My Worksheet‘)
worksheet.write(0, 0, label = ‘Row 0, Column 0 Value‘)
workbook.save(‘Excel_Workbook.xls‘)

Formatting the Contents of a Cell
import xlwt
workbook = xlwt.Workbook(encoding = ‘ascii‘)
worksheet = workbook.add_sheet(‘My Worksheet‘)
font = xlwt.Font() # Create the Font
font.name = ‘Times New Roman‘
font.bold = True
font.underline = True
font.italic = True
style = xlwt.XFStyle() # Create the Style
style.font = font # Apply the Font to the Style
worksheet.write(0, 0, label = ‘Unformatted value‘)
worksheet.write(1, 0, label = ‘Formatted value‘, style) # Apply the Style to the Cell
workbook.save(‘Excel_Workbook.xls‘)

Attributes of the Font Object
font.bold = True # May be: True, False
font.italic = True # May be: True, False
font.struck_out = True # May be: True, False
font.underline = xlwt.Font.UNDERLINE_SINGLE # May be: UNDERLINE_NONE, UNDERLINE_SINGLE, UNDERLINE_SINGLE_ACC, UNDERLINE_DOUBLE, UNDERLINE_DOUBLE_ACC
font.escapement = xlwt.Font.ESCAPEMENT_SUPERSCRIPT # May be: ESCAPEMENT_NONE, ESCAPEMENT_SUPERSCRIPT, ESCAPEMENT_SUBSCRIPT
font.family = xlwt.Font.FAMILY_ROMAN # May be: FAMILY_NONE, FAMILY_ROMAN, FAMILY_SWISS, FAMILY_MODERN, FAMILY_SCRIPT, FAMILY_DECORATIVE
font.charset = xlwt.Font.CHARSET_ANSI_LATIN # May be: CHARSET_ANSI_LATIN, CHARSET_SYS_DEFAULT, CHARSET_SYMBOL, CHARSET_APPLE_ROMAN, CHARSET_ANSI_JAP_SHIFT_JIS, CHARSET_ANSI_KOR_HANGUL, CHARSET_ANSI_KOR_JOHAB, CHARSET_ANSI_CHINESE_GBK, CHARSET_ANSI_CHINESE_BIG5, CHARSET_ANSI_GREEK, CHARSET_ANSI_TURKISH, CHARSET_ANSI_VIETNAMESE, CHARSET_ANSI_HEBREW, CHARSET_ANSI_ARABIC, CHARSET_ANSI_BALTIC, CHARSET_ANSI_CYRILLIC, CHARSET_ANSI_THAI, CHARSET_ANSI_LATIN_II, CHARSET_OEM_LATIN_I
font.colour_index = ?
font.get_biff_record = ?
font.height = 0x00C8 # C8 in Hex (in decimal) = 10 points in height.
font.name = ?
font.outline = ?
font.shadow = ?

Setting the Width of a Cell
import xltw
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet(‘My Sheet‘)
worksheet.write(0, 0, ‘My Cell Contents‘)
worksheet.col(0).width = 3333 # 3333 = 1" (one inch).
workbook.save(‘Excel_Workbook.xls‘)

Entering a Date into a Cell
import xlwt
import datetime
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet(‘My Sheet‘)
style = xlwt.XFStyle()
style.num_format_str = ‘M/D/YY‘ # Other options: D-MMM-YY, D-MMM, MMM-YY, h:mm, h:mm:ss, h:mm, h:mm:ss, M/D/YY h:mm, mm:ss, [h]:mm:ss, mm:ss.0
worksheet.write(0, 0, datetime.datetime.now(), style)
workbook.save(‘Excel_Workbook.xls‘)

Adding a Formula to a Cell
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet(‘My Sheet‘)
worksheet.write(0, 0, 5) # Outputs 5
worksheet.write(0, 1, 2) # Outputs 2
worksheet.write(1, 0, xlwt.Formula(‘A1*B1‘)) # Should output "10" (A1[5] * A2[2])
worksheet.write(1, 1, xlwt.Formula(‘SUM(A1,B1)‘)) # Should output "7" (A1[5] + A2[2])
workbook.save(‘Excel_Workbook.xls‘)

Adding a Hyperlink to a Cell
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet(‘My Sheet‘)
worksheet.write(0, 0, xlwt.Formula(‘HYPERLINK("http://www.google.com";"Google")‘)) # Outputs the text "Google" linking to http://www.google.com
workbook.save(‘Excel_Workbook.xls‘)

Merging Columns and Rows
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet(‘My Sheet‘)
worksheet.write_merge(0, 0, 0, 3, ‘First Merge‘) # Merges row 0‘s columns 0 through 3.
font = xlwt.Font() # Create Font
font.bold = True # Set font to Bold
style = xlwt.XFStyle() # Create Style
style.font = font # Add Bold Font to Style
worksheet.write_merge(1, 2, 0, 3, ‘Second Merge‘, style) # Merges row 1 through 2‘s columns 0 through 3.
workbook.save(‘Excel_Workbook.xls‘)

Setting the Alignment for the Contents of a Cell
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet(‘My Sheet‘)
alignment = xlwt.Alignment() # Create Alignment
alignment.horz = xlwt.Alignment.HORZ_CENTER # May be: HORZ_GENERAL, HORZ_LEFT, HORZ_CENTER, HORZ_RIGHT, HORZ_FILLED, HORZ_JUSTIFIED, HORZ_CENTER_ACROSS_SEL, HORZ_DISTRIBUTED
alignment.vert = xlwt.Alignment.VERT_CENTER # May be: VERT_TOP, VERT_CENTER, VERT_BOTTOM, VERT_JUSTIFIED, VERT_DISTRIBUTED
style = xlwt.XFStyle() # Create Style
style.alignment = alignment # Add Alignment to Style
worksheet.write(0, 0, ‘Cell Contents‘, style)
workbook.save(‘Excel_Workbook.xls‘)

Adding Borders to a Cell
# Please note: While I was able to find these constants within the source code, on my system (using LibreOffice,) I was only presented with a solid line, varying from thin to thick; no dotted or dashed lines.
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet(‘My Sheet‘)
borders = xlwt.Borders() # Create Borders
borders.left = xlwt.Borders.DASHED # May be: NO_LINE, THIN, MEDIUM, DASHED, DOTTED, THICK, DOUBLE, HAIR, MEDIUM_DASHED, THIN_DASH_DOTTED, MEDIUM_DASH_DOTTED, THIN_DASH_DOT_DOTTED, MEDIUM_DASH_DOT_DOTTED, SLANTED_MEDIUM_DASH_DOTTED, or 0x00 through 0x0D.
borders.right = xlwt.Borders.DASHED
borders.top = xlwt.Borders.DASHED
borders.bottom = xlwt.Borders.DASHED
borders.left_colour = 0x40
borders.right_colour = 0x40
borders.top_colour = 0x40
borders.bottom_colour = 0x40
style = xlwt.XFStyle() # Create Style
style.borders = borders # Add Borders to Style
worksheet.write(0, 0, ‘Cell Contents‘, style)
workbook.save(‘Excel_Workbook.xls‘)

Setting the Background Color of a Cell
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet(‘My Sheet‘)
pattern = xlwt.Pattern() # Create the Pattern
pattern.pattern = xlwt.Pattern.SOLID_PATTERN # May be: NO_PATTERN, SOLID_PATTERN, or 0x00 through 0x12
pattern.pattern_fore_colour = 5 # May be: 8 through 63. 0 = Black, 1 = White, 2 = Red, 3 = Green, 4 = Blue, 5 = Yellow, 6 = Magenta, 7 = Cyan, 16 = Maroon, 17 = Dark Green, 18 = Dark Blue, 19 = Dark Yellow , almost brown), 20 = Dark Magenta, 21 = Teal, 22 = Light Gray, 23 = Dark Gray, the list goes on...
style = xlwt.XFStyle() # Create the Pattern
style.pattern = pattern # Add Pattern to Style
worksheet.write(0, 0, ‘Cell Contents‘, style)
workbook.save(‘Excel_Workbook.xls‘)

TODO: Things Left to Document
- Panes -- separate views which are always in view
- Border Colors (documented above, but not taking effect as it should)
- Border Widths (document above, but not working as expected)
- Protection
- Row Styles
- Zoom / Manification
- WS Props?
Source Code for reference available at: https://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/

http://www.youlikeprogramming.com/2011/04/examples-generating-excel-documents-using-pythons-xlwt/

标签: python excel

原文地址:https://www.cnblogs.com/xinxihua/p/12635197.html

时间: 2024-10-07 15:30:37

xls4-想要使用Python的xlwt设置单元格的背景色。的相关文章

python xlwt 设置单元格样式

使用xlwt中的Alignment来设置单元格的对齐方式,其中horz代表水平对齐方式,vert代表垂直对齐方式. VERT_TOP = 0x00 上端对齐 VERT_CENTER = 0x01 居中对齐(垂直方向上) VERT_BOTTOM = 0x02 低端对齐 HORZ_LEFT = 0x01 左端对齐 HORZ_CENTER = 0x02 居中对齐(水平方向上) HORZ_RIGHT = 0x03 右端对齐 import xlwt def run(): wk = xlwt.Workboo

支持将数据导出到Excel文档的时候设置单元格格式的.NET控件Spire.DataExport

Spire.DataExport for .NET是e-iceblue公司推出的一款数据导出类.NET控件.作为一款专业的数据导出控件,Spire.DataExport for .NET可以帮助开发人员轻松快速的从各种主流数据库中导出数据并存储于各种文件格式中.他支持从SQL Command, DataTable,ListView中导出数据并存储于MS Excel,MS Word, HTML, XML, PDF, MS Access, DBF, SQL Script, SYLK, DIF, CS

Excel导出时设置单元格的格式为文本

问题: 用excel导出数据时,如何设置单元格格式的数字分类为"文本",默认是"常规"? 比如:导出编码0235A089,在Excel查看默认显示的是没有前面的0. 解决方法: 用设置单元格的 NumberFormatLocal 属性即可: xlapp.Selection.NumberFormatLocal = "@" Excel导出时设置单元格的格式为文本,布布扣,bubuko.com

NPOI 生成Excel (单元格合并、设置单元格样式:字段,颜色、设置单元格为下拉框并限制输入值、设置单元格只能输入数字等)

NPIO源码地址:https://github.com/tonyqus/npoi NPIO使用参考:源码中的 NPOITest项目 下面代码包括: 1.包含多个Sheet的Excel 2.单元格合并 3.设置单元格样式:字段,颜色 4.设置单元格为下拉框并限制输入值 5.设置单元格只能输入数字 // // GET: /Excel/ public ActionResult Write() { var workbook = new HSSFWorkbook();//从流内容创建Workbook对象

firefox ie 设置单元格宽度 td width 有bug,不能正常工作。以下方式可以解决

1. firefox ie 设置单元格宽度 td width 有bug,不能正常工作.以下方式可以解决 jqElement.css({ 'min-width': srcth1.width() + "px", 'width': srcth1.width() + "px" }); 2.不要使用CellSpacing  CellPadding,要不效果错误.

用NPOI创建Excel、合并单元格、设置单元格样式、边框的方法

今天在做项目中,遇到使用代码生成具有一定样式的Excel,找了很多资料,最后终于解决了,Excel中格式的设置,以及单元格的合并等等.下面就介绍下,使用NPOI类库操作Excel的方法. 1.首先我们先在内存中生成一个Excel文件,代码如下:   HSSFWorkbook book = new HSSFWorkbook();        ISheet sheet = book.CreateSheet("Sheet1"); 2.然后在新创建的sheet里面,创建我们的行和列,代码如下

Android给GridView设置单元格分割线

给GridView设置单元格分割线有两种方法,一种是设置背景图片设置分割线,另外一种是自定义GridView重绘视图设置分割线.重绘方法代码如下: public class LineGridView extends GridView{ public LineGridView(Context context) { super(context); // TODO Auto-generated constructor stub } public LineGridView(Context context

【web开发】☆★之利用POI操作Excel表格系列教程【8】设置单元格对其方式

[web开发]☆★之利用POI操作Excel表格系列教程[8]设置单元格对其方式 package csg.xiaoye.poidemo; import java.io.FileOutputStream; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HS

123批量添加和删除单元格(扩展知识:设置单元格的尺寸和颜色)

效果如下: ViewController.h 1 #import <UIKit/UIKit.h> 2 3 @interface ViewController : UITableViewController 4 @property (strong, nonatomic) NSMutableArray *mArrDataSource; 5 6 @end ViewController.m 1 #import "ViewController.h" 2 3 @interface Vi