您的位置:首页 > 编程语言 > Python开发

php中使用python生成excel报表

2016-10-31 11:36 453 查看
python脚本create_excel.py:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import xlwt,sys,json
from datetime import date,datetime
def set_style(style,patterni,bgcolor_index):
patterni.pattern=1 #设置底纹的图案索引,1为实心,2为50%灰色,对应为excel文件单元格格式中填充中的图案样式
patterni.pattern_fore_colour=bgcolor_index #设置底纹的前景色,对应为excel文件单元格格式中填充中的背景色
patterni.pattern_back_colour=35 #设置底纹的背景色,对应为excel文件单元格格式中填充中的图案颜色
style.pattern=patterni #为样式设置图案
return style
if __name__ == '__main__':
if len(sys.argv)<3:
print '参数错误'
exit(0)
cache_path = sys.argv[1]
excel_title = unicode(sys.argv[2], "UTF-8")
cache_source = open(cache_path,'r')
try:
cache_content = cache_source.read()
finally:
cache_source.close()
json_body = json.loads(cache_content)
f = xlwt.Workbook()
st = f.add_sheet(excel_title,cell_overwrite_ok=True)
style = xlwt.XFStyle() #初始化样式
patterni= xlwt.Pattern() #为样式创建图案
for vi in range(0,len(json_body['value'])):
if json_body['value'][vi][3]!=-1:
st.write(json_body['value'][vi][0],json_body['value'][vi][1],json_body['value'][vi][2],set_style(style,patterni,json_body['value'][vi][3]))
else:
st.write(json_body['value'][vi][0],json_body['value'][vi][1],json_body['value'][vi][2])
for mi in range(0,len(json_body['merge'])):
if json_body['merge'][mi][5]!=-1:
st.write_merge(json_body['merge'][mi][0],json_body['merge'][mi][1],json_body['merge'][mi][2],json_body['merge'][mi][3],json_body['merge'][mi][4],set_style(style,patterni,json_body['merge'][mi][5]))
else:
st.write_merge(json_body['merge'][mi][0],json_body['merge'][mi][1],json_body['merge'][mi][2],json_body['merge'][mi][3],json_body['merge'][mi][4])
f.save(cache_path+'.xls') #保存文件
print cache_path+'.xls'


python的xlwt中设置颜色用数字表示,下面生成数字与颜色对应的表格,方便颜色取值:

# -*- coding: utf-8 -*-
import xlwt
if __name__ == '__main__':
#新建一个excel文件
file=xlwt.Workbook()
#新建一个sheet
table=file.add_sheet('sheet name',cell_overwrite_ok=True)
for i in range(0,256):
stylei= xlwt.XFStyle() #初始化样式
patterni= xlwt.Pattern() #为样式创建图案
patterni.pattern=1 #设置底纹的图案索引,1为实心,2为50%灰色,对应为excel文件单元格格式中填充中的图案样式
patterni.pattern_fore_colour=i #设置底纹的前景色,对应为excel文件单元格格式中填充中的背景色
patterni.pattern_back_colour=35 #设置底纹的背景色,对应为excel文件单元格格式中填充中的图案颜色
stylei.pattern=patterni #为样式设置图案
table.write(i,0,i,stylei) #使用样式
file.save('colour.xls')


上面create_excel.py脚本创建excel接收两个参数,第一个参数为缓存文件地址,第二个参数为excel中sheet的名字:
第一个参数缓存文件内容格式(php生成代码):

$set_value_cmd = array();//设置单元格数值所有参数 array('行','列','值','背景色索引,不设置写为-1') 二维
$merge_cmd = array();//所有需要合并的单元格的参数 array('行开始','行结束','列开始','列结束','值','背景色索引,不设置写为-1') 二维
$cache_data = json_encode(array('value'=>$set_value_cmd,'merge'=>$merge_cmd));
$file = "create_excel_cache/".$_USER->id.time();
file_put_contents($file, $cache_data);
$out = popen("./create_excel.py  '{$file}' '报表'", "r");
$file_return = '/';//python脚本返回的xls文件地址
while(!feof($out)) {
$buffer = fgets($out);
$file_return .= $buffer;
}
pclose($out);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: