来公司的第一个任务,就是用Python写一个自动处理excel的脚本,需要实现的功能为:1.读取外部的参数 2.从一个excel表格中读取公式和文本信息 3.将1中的参数带入到2中的公式中计算出结果并写入一个新建的excel表格中。
于是我的Python学习之路就此拉开序幕,学习之路需要脚踏实地,一步一个脚印,勉励自己能够坚持的记录下去~
项目的源代码如下:
#! /usr/bin/env python
# -*- coding:utf-8 –*-
import xlrd
import xlwt
#import sys
#reload(sys)
#sys.setdefaultencoding('utf-8')
def format_xlsx():
font0 = xlwt.Font()
font0.name = 'Times New Roman'
font0.colour_index = 2
font0.height=225
font0.bold = True
alignment = xlwt.Alignment()
alignment.horz = xlwt.Alignment.HORZ_CENTER
pattern = xlwt.Pattern()
pattern.pattern = xlwt.Pattern.SOLID_PATTERN
pattern.pattern_fore_colour = 5
style = xlwt.XFStyle()
style.font=font0
style.alignment = alignment
style.pattern = pattern
return style
def open_xlsx(file='f.xlsx'):
data=xlrd.open_workbook(file)
return data
def cal_xlsx(file='f.xlsx',sheet_index=0,width=1,height=1,frames=1,style=1,save_file='result.xlsx'):
data=open_xlsx(file)
table=data.sheets()[sheet_index]
#---------------------
file_w=xlwt.Workbook()
table_w=file_w.add_sheet(data.sheet_names()[sheet_index],cell_overwrite_ok=True)
#--------------------
tab_row=table.nrows
tab_col=table.ncols
rowv=table.row_values(0)
colv=table.col_values(0)
for x in range(1,tab_col):
table_w.write_merge(0,0,(x*2-1),x*2,rowv[x],style)
table_w.col(x*2-1).width = 8000
for y in range(0,tab_row):
table_w.write(y,0,colv[y],style)
for row in range(1,table.nrows):
for col in range(1,table.ncols):
formula0=table.cell(row,col).value
table_w.write(row,col*2-1,formula0.replace('width',str(width)).replace('height',str(height)).replace('frames',str(frames)))
for row in range(1,table.nrows):
for col in range(1,table.ncols):
formula0=table.cell(row,col).value
table_w.write(row,col*2,eval(formula0))
file_w.save(save_file)
return 0
def main():
print "1.请输入需要加载的参数值>>>"
while(1):
try:
width=input("请输入width的值:")
except Exception,e:
print '输入的数据不合法,请输入【整数】或者【浮点数】!',e
else:
break
while(1):
try:
height=input("请输入height的值:")
except Exception,e:
print '输入的数据不合法,请输入【整数】或者【浮点数】!',e
else:
break
while(1):
try:
frames=input("请输入frames的值:")
except Exception,e:
print '输入的数据不合法,请输入【整数】或者【浮点数】!',e
else:
break
print "2.请输入需要加载公式的文档路径名>>>"
while(1):
try:
path=raw_input("请输入EXCL路径名称:")
except Exception,e:
print '输入的数据不合法,请输入完整的路径名称!',e
else:
break
print "3.请输入需要处理的表单序号>>>"
while(1):
try:
index=input("请输入EXCL表单序号:")
except Exception,e:
print '输入的数据不合法,请输入【整数】!',e
else:
break
print "4.请输入生成EXCL的名称[xxx.xlsx]>>>"
while(1):
try:
savefile=raw_input("请输入保存处理结果的EXCL名称:")
except Exception,e:
print '输入的数据不合法!',e
else:
break
style=format_xlsx()
try:
cal_xlsx(path,index,width,height,frames,style,savefile)
except Exception,e:
print '处理失败!',e
else:
print '表格生成成功,请查询结果!'
main()
下面说明在编写这个程序时遇到的问题和解决的方法:
1.
#! /usr/bin/env python
必须置于文件的第一行,用于告诉操作系统使用哪种程序去运行文件中的代码,并指出解释程序的位置,如果使用 ./xxx.py 的方法运行脚本文件那么这行代码是必不可少的,如果运行时使用 python xxx.py 的方法显式的指出是使用Python解释器运行文件代码,则可以不需要这行代码。
2.
# -*- coding:utf-8 –*-
或者
#coding=utf-8
必须在文件的第一行或者第二行指定该编码声明(包括空行)。Python默认的脚本文件都是使用ASCII编码的,当文件中出现了汉字等非ASCII编码范围的字符时,就需要该条代码来修正。该行代码可以把默认的脚本编码方式修改为UTF-8,这是一种支持汉字的编码方式。既然提到了编码,那么这里就展开说明一下。
ASCII编码
一个字节8位,可以表示256种不同的状态,也就可以代表256种字符。上个世纪60年代,美国制定了这套字符编码,对英语字符与二进制位之间的关系,做了统一规定。这被称为ASCII码,一直沿用至今。ASCII码一共规定了128个字符的编码,使用了后7位,第8位统一规定为0。
非ASCII编码
汉字等非英文字母组合表示的字符,使用ASCII编码就不能表示,于是便需要其他的编码方式,比如汉字可以使用GB2312编码,使用两个字节表示一个汉字。理论上可以表示65536个汉字符号。如果使用不同的编码编码和解码文件就会出现乱码,所以就需要一个统一的编码出现,这就是Unicode。UTF-8就是一种Unicode的实现方式之一,其使用1-4个字节表示一个符号,根据不同的符号变化字节的长度。
#import sys
#reload(sys)
#sys.setdefaultencoding('utf-8')
这行虽然注释了,但是还是应该记录一下。脚本文件默认的解码方式为ASCII。使用UTF-8编码而使用ASCII解码就会出现错误,为了实现编码和解码的统一,我们就需要改变默认的编码方式。
codes:这个模块定了标准Python解码器(编码器和解码器)的基类,并提供了内部Python编码器注册表的入口,该注册表管理编码器和错误处理查找进程。
codecs.
encode
(obj[,encoding[,errors]]
codecs.
decode
(obj[,encoding[,errors]])
两个对象均使用编码器注册编码,默认的编码是ascii
3.
def format_xlsx():
font0 = xlwt.Font()
font0.name = 'Times New Roman'
font0.colour_index = 2
font0.height=225
font0.bold = True
alignment = xlwt.Alignment()
alignment.horz = xlwt.Alignment.HORZ_CENTER
pattern = xlwt.Pattern()
pattern.pattern = xlwt.Pattern.SOLID_PATTERN
pattern.pattern_fore_colour = 5
style = xlwt.XFStyle()
style.font=font0
style.alignment = alignment
style.pattern = pattern
return style
设置excel的格式。拿字体举例,首先实例化一个字体类,然后设置它的name,colour,height,width,bold等属性,实例化一个style类,将填充好的字体类赋值给style中的font属性中。XFStyle类包含如下表所示的几种属性。
Group | Attributes |
---|---|
Number format | Number format index (index to FORMAT record) |
Font | Font index (index to FONT record) |
Alignment | Horizontal and vertical alignment, text wrap, indentation,orientation/rotation, text direction |
Border | Border line styles and colours |
Background | Background area style and colours |
Protection | Cell locked, formula hidden |
style = xlwt.easyxf('pattern: pattern solid, fore_colour light_blue;'
'font: colour white, bold True;')
4.
cal_xlsx(file='f.xlsx',sheet_index=0,width=1,height=1,frames=1,style=1,save_file='result.xlsx'):
这里需要注意的时变量的顺序问题,有默认值的参数必须放到没有默认值的参数之前,
def func(y=2, x):这种函数是不被允许的,运行会报错。
5.
file_w=xlwt.Workbook()
table_w=file_w.add_sheet(data.sheet_names()[sheet_index],cell_overwrite_ok=True)
xlwt.Workbook.
Workbook
(encoding='ascii',style_compression=0)
6.
table_w.write(row,col*2,eval(formula0))
eval() 函数可以计算传入其中的表达式的值。