python操作xlsx文件的包openpyxl实例

Python扩展库openpyxl,可以操作07版以上的xlsx文件。可以创建工作簿、选择活动工作表、写入单元格数据,设置单元格字体颜色、边框样式,合并单元格,设置单元格背景等等。

需要增加可以颜色进入包安装目录的

your_pthon_path/site-packages/openpyxl/styles

修改colors.py文件下的

COLOR_INDEX = (
 '00000000', '00FFFFFF', '00FF0000', '0000FF00', '000000FF', #0-4
 '00FFFF00', '00FF00FF', '0000FFFF', '00000000', '00FFFFFF', #5-9
 '00FF0000', '0000FF00', '000000FF', '00FFFF00', '00FF00FF', #10-14
 '0000FFFF', '00800000', '00008000', '00000080', '00808000', #15-19
 '00800080', '00008080', '00C0C0C0', '00808080', '009999FF', #20-24
 '00993366', '00FFFFCC', '00CCFFFF', '00660066', '00FF8080', #25-29
 '000066CC', '00CCCCFF', '00000080', '00FF00FF', '00FFFF00', #30-34
 '0000FFFF', '00800080', '00800000', '00008080', '000000FF', #35-39
 '0000CCFF', '00CCFFFF', '00CCFFCC', '00FFFF99', '0099CCFF', #40-44
 '00FF99CC', '00CC99FF', '00FFCC99', '003366FF', '0033CCCC', #45-49
 '0099CC00', '00FFCC00', '00FF9900', '00FF6600', '00666699', #50-54
 '00969696', '00003366', '00339966', '00003300', '00333300', #55-59
 '00993300', '00993366', '00333399', '00333333', 'System Foreground', 'System Background' #60-64
 '00D2B48C', '0087CEFA', '0000BFFF' #自己添加的
)

以00+16进制RGB颜色代码的形式即可

自己写的一个生成xlsx文件的代码:

#!/usr/bin/env python
#-*- coding: utf-8 -*-
import openpyxl
from openpyxl import Workbook
from openpyxl.styles import colors,Font,Border,Side,PatternFill,Alignment
wb = Workbook() #创建工作簿
ws = wb.active #激活工作簿
ws.merge_cells('C3:E3') #合并单元格
ws.merge_cells('C4:E4')
ws.merge_cells('C20:I20')
ws.merge_cells('C21:I21')
left, right, top, bottom = [Side(style='thin', color='000000')]*4 #设置单元格边框属性
border = Border(left=left, right=right, top=top, bottom=bottom) #设置单元格边框格式
fill1 = PatternFill(start_color = 'FFFF00', end_color = 'FFFF00', fill_type = 'solid') #设置单元格背景色
fill2 = PatternFill(start_color = 'D2B48C', end_color = 'D2B48C', fill_type = 'solid')
fill3 = PatternFill(start_color = '00BFFF', end_color = '00BFFF', fill_type = 'solid')
fill4 = PatternFill(start_color = 'FF0000', end_color = 'FF0000', fill_type = 'solid')
align1 = Alignment(horizontal='center', vertical='center') #设置文本对齐
align2 = Alignment(horizontal='left', vertical='center')
for i in range(3,22):
 for col in 'CDEFGHIJK':
 ws[col+str(i)].border = border #给每个单元格设置相应的格式 
 #ws[col+str(3)].fill = fill1
 #ws[col+str(i)].alignment = align
for col in 'CDEFGHIJK':
 ws[col+str(3)].fill = fill1
 ws[col+str(20)].fill = fill3
 ws[col+str(21)].fill = fill4
 for i in range(4,20):
 ws[col+str(i)].fill = fill2
for col in 'CDEFGHIJK':
 ws[col+str(3)].alignment = align1
for i in range(4,22):
 for col in 'CDE':
 ws[col+str(i)].alignment = align2
for col in 'CDEFGHIJK':
 ws[col+str(3)] = 'test1' #单元格赋值
for i in range(3,22):
 for col in 'CDE':
 if i in range(5,20) and col == 'C':
  pass
 else:
  ws[col+str(i)] = 'test2'
for i in range(4,20):
 for col in 'EFGHIJK':
 ws[col+str(i)] = 50
for i in range(20,22):
 for col in 'JK':
 ws[col+str(i)] = 100
wb.save('test.xlsx') #保存文件

单元格字体等也可以使用相应的模块去设置。

相关推荐