本人初步学习Python,用python的第一个项目就是 生成报告,先将代码贴上,以后将我的心得写一下,以避免大家再次踩坑

#coding: utf-8
# from LaserDB import LaserDBimport sys
if 'threading' in sys.modules:del sys.modules['threading']
import sqlite3 as db
import os
import json
import re
import matplotlib.pyplot as plt
from matplotlib import font_manager
# cn_font = 'Droid Sans Fallback'
cn_font = font_manager.FontProperties(fname='/usr/share/fonts/truetype/arphic/uming.ttc')
# cn_font = font_manager.FontProperties(fname='/usr/share/fonts/truetype/arphic/ukai.ttc')
import cStringIO
from reportlab.lib.utils import ImageReaderimport time
from reportlab.lib import colors
from reportlab.lib.enums import TA_JUSTIFY,TA_CENTER
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, PageBreak, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch, cm, mmimport reportlab.rl_config
reportlab.rl_config.warnOnMissingFontGlyphs = 0
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen import canvas
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
pdfmetrics.registerFont(UnicodeCIDFont('STSong-Light'))from reportlab.lib import fonts
fonts.addMapping('STSong-Light', 0, 0, 'STSong-Light')
fonts.addMapping('STSong-Light', 0, 1, 'STSong-Light')
fonts.addMapping('STSong-Light', 1, 0, 'STSong-Light')
fonts.addMapping('STSong-Light', 1, 1, 'STSong-Light')from reportlab.rl_config import defaultPageSize
PAGE_HEIGHT=defaultPageSize[1]; PAGE_WIDTH=defaultPageSize[0]import copy
import datetimeframeNum = 0
laserNum = 0pdfTitle_name   = {}
DBfile_name     = {}
outputfile_name = {}
LidarId         = {}
LidarName       = {}
time            = {}
testPeople      = {}
distance        = {}
lidarIntensity  = {}
temperature     = {}boardMapList    = {}story=[]
distSet = []
dataValue = []ispass = 1# Font format
styles=getSampleStyleSheet()
styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
styles.add(ParagraphStyle(name='Center-green', alignment=TA_CENTER,textColor=colors.green))
styles.add(ParagraphStyle(name='Center-red', alignment=TA_CENTER,textColor=colors.red))
styles.add(ParagraphStyle(name='green',textColor=colors.green))
styles.add(ParagraphStyle(name='red',textColor=colors.red))
styles.add(ParagraphStyle(name='black',textColor=colors.black))
styles.add(ParagraphStyle(name='Center-black',alignment=TA_CENTER,textColor=colors.black))
styles.add(ParagraphStyle(name='FirstTitle', alignment=TA_CENTER))
styles.add(ParagraphStyle(name='SecondTitle', alignment=0))
styles.add(ParagraphStyle(name='ThirdTitle', alignment=0,leftIndent=24))# Place the points in the database into this class.
class distanceData:def __init__(self, laser, maxdistance,avgdistance,mindistance ,temperature,threshold, intensity, ispass):self.laser = laserself.maxdistance = maxdistanceself.avgdistance = avgdistanceself.mindistance = mindistanceself.temperature = temperatureself.threshold = thresholdself.intensity = intensityself.ispass  = ispass# add page number function
def addExtraInfo(canvas, doc):'''Add the page number'''page_num = canvas.getPageNumber()text = "-%s-" % page_numcanvas.drawCentredString(PAGE_WIDTH/2.0, 20*mm, text)# set tab title for pdfcanvas.setTitle("Hesaitech")styleSheet = getSampleStyleSheet()style = styleSheet['BodyText']corner=Paragraph('''<a href="#page1">%s</a>''' % u'\u2191',style)w,h = corner.wrapOn(canvas, 10*mm, 10*mm)def parserDB(db_filename,db_tablename):conn = db.connect(db_filename)  # 该 API 打开一个到 SQLite 数据库文件 database 的链接,如果数据库成功打开,则返回一个连接对象    cur=conn.cursor()        # 该例程创建一个 cursor,将在 Python 数据库编程中用到。conn.row_factory=db.Row     # 可访问列信息tableName = "select * from " + db_tablenamecur.execute(tableName)    # 该例程执行一个 SQL 语句#cur.execute("select * from wave_distance")    # 该例程执行一个 SQL 语句rows=cur.fetchall()      # 该例程获取查询结果集中所有(剩余)的行,返回一个列表。当没有可用的行时,则返回一个空的列表。return rows
# generate the wave report
def WaveReportchart(db_filename,db_tablename,tableTitle):global laserNumglobal dataValueglobal ispassispass = 1;# chart pdf the first page# the chart headerCNStyle = copy.deepcopy(styles['Center']) CNStyle.fontName ='STSong-Light'story.append(Paragraph('<font size=15><a name="page1"/>%s</font>'%(tableTitle),CNStyle))story.append(Spacer(1, 15))component_data = []ChartLine = []ChartSecondLine = []partDataValue = []# Set the table head ChartLine.append(Paragraph('<font>通道</font>',CNStyle))ChartLine.append(Paragraph('<font>测距能力(米)</font>',CNStyle))ChartLine.append(Paragraph('<font>测距能力(米)</font>',CNStyle))ChartLine.append(Paragraph('<font>测距能力(米)</font>',CNStyle))ChartLine.append(Paragraph('<font>测距下限\n(米)</font>',CNStyle))ChartLine.append(Paragraph('<font>反射率\n(%)</font>',CNStyle))ChartLine.append(Paragraph('<font>测试温度\n(℃)</font>',CNStyle))ChartLine.append(Paragraph('<font>是否通过\n(平均值)</font>',CNStyle))component_data.append(ChartLine)ChartSecondLine.append(Paragraph('<font></font>',CNStyle))ChartSecondLine.append(Paragraph('<font>最大值</font>',CNStyle))ChartSecondLine.append(Paragraph('<font>平均值</font>',CNStyle))ChartSecondLine.append(Paragraph('<font>最小值</font>',CNStyle))ChartSecondLine.append(Paragraph('<font></font>',CNStyle))ChartSecondLine.append(Paragraph('<font></font>',CNStyle))ChartSecondLine.append(Paragraph('<font></font>',CNStyle))ChartSecondLine.append(Paragraph('<font></font>',CNStyle))component_data.append(ChartSecondLine)#parser database and place data to the point classlines = parserDB(db_filename,db_tablename)for line in lines:value = [s for s in line]oneline = distanceData(value[0],value[1],value[3],value[2],value[4],value[5],value[6],int(value[7]))partDataValue.append(oneline)dataValue = partDataValue#Arranging data into rows and rows of informationfor oneChannel in dataValue:partLaserValue = []if (oneChannel.ispass == 0):result = "fail"typeFace = "Center-red"ispass = 0else:result = "pass"typeFace = "Center-black"if (int(oneChannel.avgdistance) == 0):avgdistance_result = "Unmeasurable"else:avgdistance_result = oneChannel.avgdistanceif (int(oneChannel.maxdistance) == 0):maxdistance_result = "Unmeasurable"else:maxdistance_result = oneChannel.maxdistanceif (int(oneChannel.mindistance) == 0):mindistance_result = "Unmeasurable"else:mindistance_result = oneChannel.mindistancepartLaserValue.append(Paragraph('''<font size=8>%s</font>''' % (oneChannel.laser),styles[typeFace]))partLaserValue.append(Paragraph('''<font size=8>%s</font>''' % (maxdistance_result),styles[typeFace]))        partLaserValue.append(Paragraph('''<font size=8>%s</font>''' % (avgdistance_result),styles[typeFace]))partLaserValue.append(Paragraph('''<font size=8>%s</font>''' % (mindistance_result),styles[typeFace]))partLaserValue.append(Paragraph('''<font size=8>%s</font>''' % (oneChannel.threshold),styles[typeFace]))partLaserValue.append(Paragraph('''<font size=8>%s</font>''' % (oneChannel.intensity),styles[typeFace]))partLaserValue.append(Paragraph('''<font size=8>%s</font>''' % (oneChannel.temperature),styles[typeFace]))partLaserValue.append(Paragraph('''<font size=8>%s</font>''' %(result),styles[typeFace]))component_data.append(partLaserValue);# Set tabular format component_table = Table(component_data, colWidths=65)component_table.setStyle(TableStyle([('FONTSIZE', (-1, -1), (-2, -2), 10),('LINEBEFORE', (0, 0), (0, -1), 0.1, colors.grey), ('SPAN',(1,0),(3,0)),('SPAN',(0,1),(0,0)),('SPAN',(4,1),(4,0)),('SPAN',(5,1),(5,0)),('SPAN',(6,1),(6,0)),('SPAN',(7,1),(7,0)),('GRID', (0, 0), (-1, -1), 0.5, colors.black)]))if (ispass == 0):CNStyle = copy.deepcopy(styles['red']) CNStyle.fontName ='STSong-Light'story.append(Paragraph('<font size=15>测试结果:fail</font>',CNStyle))else:CNStyle = copy.deepcopy(styles['green']) CNStyle.fontName ='STSong-Light'story.append(Paragraph('<font size=15>测试结果:pass</font>',CNStyle))story.append(Spacer(1, 15))story.append(component_table)story.append(PageBreak())# add pdf title
def pdfTitle(LidarName):CNStyle = copy.deepcopy(styles['Center']) CNStyle.fontName ='STSong-Light'story.append(Paragraph('<font size=25><a name="page1"/>%s 测远能力报告</font>'%(LidarName) ,CNStyle))story.append(Spacer(1, 50))
def pdfBasicInfomation():global LidarIdglobal LidarNameglobal testPeopleglobal distanceglobal lidarIntensityglobal temperaturetimeDate = datetime.datetime.now().strftime('%Y-%m-%d')timeNow = datetime.datetime.now().strftime('%H:%M:%S')firstLine  = [];secondLine = [];thirdLine  = [];fourthLine = [];component_data = []CNStyle = copy.deepcopy(styles['Center']) CNStyle.fontName ='STSong-Light'story.append(Paragraph('<font size=15><a name="page1"/>测试基本信息</font>',CNStyle))story.append(Spacer(1, 15))firstLine.append(Paragraph('<font size=10>Lidar编号</font>',CNStyle))firstLine.append(Paragraph('<font size=10>Lidar型号</font>',CNStyle))firstLine.append(Paragraph('<font size=10>测试日期</font>',CNStyle))firstLine.append(Paragraph('<font size=10>生成报告时间</font>',CNStyle))component_data.append(firstLine)secondLine.append(Paragraph('<font size=10>%s</font>'%(LidarId),CNStyle))secondLine.append(Paragraph('<font size=10>%s</font>'%(LidarName),CNStyle))secondLine.append(Paragraph('<font size=10>%s</font>'%(timeDate),CNStyle))secondLine.append(Paragraph('<font size=10>%s</font>'%(timeNow),CNStyle))component_data.append(secondLine)thirdLine.append(Paragraph('<font size=10>靶板距离(m)</font>',CNStyle))thirdLine.append(Paragraph('<font size=10>靶板反射率(%)</font>',CNStyle))thirdLine.append(Paragraph('<font size=10>测试温度(℃)</font>',CNStyle))thirdLine.append(Paragraph('<font size=10>测试人员</font>',CNStyle))component_data.append(thirdLine)fourthLine.append(Paragraph('<font size=10>%s</font>'%(distance),CNStyle))fourthLine.append(Paragraph('<font size=10>%s</font>'%(lidarIntensity),CNStyle))fourthLine.append(Paragraph('<font size=10>%s</font>'%(temperature),CNStyle))fourthLine.append(Paragraph('<font size=10>%s</font>'%(testPeople),CNStyle))component_data.append(fourthLine)component_table = Table(component_data, colWidths=90)component_table.setStyle(TableStyle([('FONTSIZE', (-1, -1), (-2, -2), 10),('LINEBEFORE', (0, 0), (0, -1), 0.1, colors.grey), ('GRID', (0, 0), (-1, -1), 0.5, colors.black)]))story.append(component_table)story.append(Spacer(1, 30))
def setBasicTestInfomation(basicInfomationList):global LidarIdglobal LidarNameglobal testPeopleglobal distanceglobal lidarIntensityglobal temperature# if (len(fileNameList) != 6):#     return -1LidarId        = basicInfomationList[0]LidarName      = basicInfomationList[1]testPeople     = basicInfomationList[2]distance       = basicInfomationList[3]lidarIntensity = basicInfomationList[4]temperature    = basicInfomationList[5]return 0def setFileName(fileNameList):global pdfTitle_nameglobal DBfile_nameglobal outputfile_nameif (len(fileNameList) != 3):return -1pdfTitle_name   = fileNameList[0]DBfile_name     = fileNameList[1]outputfile_name = fileNameList[2]return 0def setPDFName(name):doc = SimpleDocTemplate(name)doc.build(story,onFirstPage=addExtraInfo, onLaterPages=addExtraInfo)def setParam(laser):global laserNum laserNum = laserreturn 0 def start():global pdfTitle_nameglobal DBfile_nameglobal outputfile_namepdfTitle(pdfTitle_name)pdfBasicInfomation()WaveReportchart(DBfile_name,"wave_distance","测远报告")setPDFName(outputfile_name)
'''
# public interface
'''
if __name__ == '__main__':argc = len(sys.argv)laserNum = int(sys.argv[1])print laserNumfileNameList=[]fileNameList.append(sys.argv[2])print sys.argv[2]fileNameList.append(sys.argv[3])print sys.argv[3]fileNameList.append(sys.argv[4])print sys.argv[4]basicInfoList = []basicInfoList.append(sys.argv[5])print sys.argv[5]basicInfoList.append(sys.argv[6])print sys.argv[6]basicInfoList.append(sys.argv[7])print sys.argv[7]basicInfoList.append(sys.argv[8])print sys.argv[8]basicInfoList.append(sys.argv[9])print sys.argv[9]basicInfoList.append(sys.argv[10])print sys.argv[10]# laserNum = 40# fileNameList = ['a','Avgwaveanalyse.db','aaaa']# basicInfoList = ['0','40p','Yulin','100','500','20.0']setFileName(fileNameList)setBasicTestInfomation(basicInfoList)setParam(laserNum)start()

python学习之生成报告相关推荐

  1. python数据分析并生成报告_pandas_profiling :教你一行代码生成数据分析报告

    分析报告全貌 什么是探索性数据分析 熟悉pandas的童鞋估计都知道pandas的describe()和info()函数,用来查看数据的整体情况,比如平均值.标准差之类,就是所谓的探索性数据分析-ED ...

  2. python数据分析并生成报告界面_如何用Python绘图和制作数据分析报告?

    Live 简介: 你要向老板汇报自己的工作成果,如果光靠生硬的语言或文字来展示,那么老板很有可能听不懂,更没有兴趣看那一堆文字.这会直接影响你的升职加薪.但是你还要还房贷.买车子.旅游.结婚.生孩子. ...

  3. Python学习之生成带logo背景图的二维码(静态和动态图)

    前言 二维码简称 QR Code(Quick Response Code),学名为快速响应矩阵码,是二维条码的一种,由日本的 Denso Wave 公司于 1994 年发明.现随着智能手机的普及,已广 ...

  4. python学习之生成一个二维码(一)

    首先,简单介绍一下二维码:二维码又称二维条码,常见的二维码为QR Code,QR全称Quick Response,是一个近几年来移动设备上超流行的一种编码方式,它比传统的Bar Code条形码能存更多 ...

  5. Python学习之生成动态二维码

    from MyQR import myqr myqr.run(     words='http://weixin.qq.com/r/kzlje9TEE4lsrZAY92yB',     # 扫描二维码 ...

  6. python学习——随机生成姓名手机号等测试数据

    随机生成姓名手机号数据 import randomdef random_name():# 删减部分,比较大众化姓氏firstName = "赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张孔 ...

  7. Python学习之生成滚动广告屏

    import os, timedef main(): # 用函数封装,可复用性会高一些(可在其他的.py文件里调用该函数.)content = ' 2019好运连连 ' for i in range( ...

  8. 【Python】Pandas profiling 生成报告并部署的一站式解决方案

    Pandas 库功能非常强大,特别有助于数据分析与处理,并为几乎所有操作提供了完整的解决方案.一种常见的Pandas函数是pandas describe.它向用户提供数据集所有特征的描述性统计摘要,尽 ...

  9. Python 可轻松生成图文并茂的PDF报告!

    大家好,reportlab是Python的一个标准库,可以画图.画表格.编辑文字,最后可以输出PDF格式.它的逻辑和编辑一个word文档或者PPT很像.有两种方法: 1)建立一个空白文档,然后在上面写 ...

最新文章

  1. 温网停赛,AI不停赛:斯坦福新研究模拟网球名将打比赛
  2. vtune下载 windows_intel vtune 介绍、安装和使用
  3. Linux安装/卸载软件教程
  4. python路径怎么找windows_如何查看 windows 中 Python安装路径
  5. git啊,你让我好费劲啊
  6. 50-10-010-配置-整体配置
  7. 《灵飞经》②东岛门人 第四章 星隐真人
  8. 基于Select模型的匿名聊天室v1.0
  9. 基于纠错编码的数字水印matlab,method robustness是什么意思
  10. AJAX-Cache:一款好用的Ajax缓存插件
  11. Codeforces Round #439 (Div. 2) E. The Untended Antiquity (hash+数状数组)
  12. 小米note2鸿蒙ROM,小米最新刷机包rom下载_奇兔rom市场
  13. matlab fminsearch 原理,Matlab利用fminsearch实现参数估计
  14. noip模拟赛 街灯
  15. kubernetes dev client-go 进入pod执行命令
  16. monkey 测试 ANR 问题 整理分析
  17. 计算机组成原理白中英第七章,计算机组成原理第七章课件(白中英版).ppt
  18. 任意四边形的面积公式
  19. vue + element 中tab标签页拖拽(拖动) sortablejs插件实现
  20. 教你更高效的管理医院设备,可别错过

热门文章

  1. 微信小程序python解析获取用户手机号_微信小程序获取用户手机号详解
  2. windows live writer 设置默认字体
  3. VB字体对话框ShowFont
  4. 计算机编程课程英语单词,计算机编程常用英语单词
  5. python表白神器原理_python仿抖音表白神器
  6. 基于JavaSwing的高级计算器
  7. 国美GOME U7 启用自带fm收音机功能,无需流量和wifi便可畅听广播.2021-12-23
  8. android 仿音悦台页面交互效果
  9. matlab绘图(其他形式的二维曲线)
  10. 转:实验3 地理空间数据可视化