예제 #1
0
파일: xq_new.py 프로젝트: HiRoad/hello
def deal_doc_task():
    file_db_base = 'd:/xq/xqfav.db'
    base_db_instance = sqlite3.connect(file_db_base)
    base_db_cursor = base_db_instance.cursor()
        
    document = Document()

    #
    base_db_cursor.execute(' select pid, title, created_at, userid, username, content from xq_fav order by username, pid')
    lists = base_db_cursor.fetchall()

    for vals in lists:
        # title
        document.add_heading( '%s - %s @%s' % (vals[0], vals[1], vals[4]), 0 )
        # content
        #try:
        generate_xq_content( document, vals[5] )
        #except:
        #    print '!--generate failed! %s' % vals[0]
        # next page
        document.add_page_break()
        #
    #
    doc_file = 'D:/xq/HiRoad_XQFav_%s.docx' % datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
    document.save(doc_file)
예제 #2
0
파일: mdoc.py 프로젝트: tuling56/Python
def mdoc():
    document = Document()
    document.add_heading("Document Title", 0)

    p = document.add_paragraph("A plain paragraph having some ")
    p.add_run("bold").bold = True
    p.add_run(" and some ")
    p.add_run("italic.").italic = True

    document.add_heading("Heading, level 1", level=1)
    document.add_paragraph("Intense quote", style="IntenseQuote")

    document.add_paragraph("first item in unordered list", style="ListBullet")
    document.add_paragraph("first item in ordered list", style="ListNumber")

    document.add_picture("monty-truth.png", width=Inches(1.25))

    table = document.add_table(rows=1, cols=3)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = "Qty"
    hdr_cells[1].text = "Id"
    hdr_cells[2].text = "Desc"
    for item in recordset:
        row_cells = table.add_row().cells
        row_cells[0].text = str(item.qty)
        row_cells[1].text = str(item.id)
        row_cells[2].text = item.desc

    document.add_page_break()

    document.save("demo.docx")
예제 #3
0
파일: views.py 프로젝트: StuJ/rua
def create_review_form(submission, review_form):
	document = Document()
	document.add_heading(submission.title, 0)
	p = document.add_paragraph('You should complete this form and then use the review page to upload it.')
	relations = models.FormElementsRelationship.objects.filter(form=review_form).order_by('order')
	for relation in relations:

		if relation.element.field_type in ['text', 'textarea', 'date', 'email']:
			document.add_heading(relation.element.name+": _______________________________", level=1)
			document.add_paragraph(relation.help_text).italic = True

		if relation.element.field_type in ['select', 'check']:
			document.add_heading(relation.element.name, level=1)
			if relation.element.field_type == 'select':
				choices = render_choices(relation.element.choices)
			else:
				choices = ['Y', 'N']

			p = document.add_paragraph(relation.help_text)
			p.add_run(' Mark your choice however you like, as long as it is clear.').italic = True
			table = document.add_table(rows=2, cols=len(choices))
			hdr_cells = table.rows[0].cells
			for i, choice in enumerate(choices):
				hdr_cells[i].text = choice[0]
			table.style = 'TableGrid'

	document.add_page_break()
	if not os.path.exists(os.path.join(settings.BASE_DIR, 'files', 'forms')):
		os.makedirs(os.path.join(settings.BASE_DIR, 'files', 'forms'))
	path = os.path.join(settings.BASE_DIR, 'files', 'forms', '%s.docx' % str(uuid4()))

	document.save(path)
	return path
예제 #4
0
파일: views.py 프로젝트: StuJ/rua
def create_completed_review_form(submission,review_id):
	document = Document()
	document.add_heading(submission.title, 0)
	review_assignment = get_object_or_404(core_models.ReviewAssignment, pk=review_id)
	if review_assignment.review_form:
		relations = models.FormElementsRelationship.objects.filter(form=review_assignment.review_form).order_by('order')
	else:
		review_assignment.review_form = submission.review_form
		review_assignment.save()
		relations = models.FormElementsRelationship.objects.filter(form=submission.review_form).order_by('order')
	
	if review_assignment.results:
		p = document.add_paragraph('%s completed this review assignment form.'% review_assignment.user.profile.full_name())
	
		data = json.loads(review_assignment.results.data)
		for relation in relations:
			v = data[relation.element.name]
			document.add_heading(relation.element.name, level=1)        
			text = BeautifulSoup(str(v[0]),"html.parser").get_text()
			document.add_paragraph(text).bold = True
			recommendations = {'accept': 'Accept','reject': 'Reject', 'revisions':'Revisions Required'}

		document.add_heading("Recommendation", level=1)
		document.add_paragraph(recommendations[review_assignment.recommendation]).italic = True
		document.add_heading("Competing Interests", level=1)
		document.add_paragraph(review_assignment.competing_interests).italic = True
	
	else:
		p = document.add_paragraph('You should complete this form and then use the review assignment page to upload it.')
	
		for relation in relations:

			if relation.element.field_type in ['text', 'textarea', 'date', 'email']:
				document.add_heading(relation.element.name+": _______________________________", level=1)
				document.add_paragraph(relation.help_text).italic = True

			if relation.element.field_type in ['select', 'check']:
				document.add_heading(relation.element.name, level=1)
				if relation.element.field_type == 'select':
					choices = render_choices(relation.element.choices)
				else:
					choices = ['Y', 'N']

				p = document.add_paragraph(relation.help_text)
				p.add_run(' Mark your choice however you like, as long as it is clear.').italic = True
				table = document.add_table(rows=2, cols=len(choices))
				hdr_cells = table.rows[0].cells
				for i, choice in enumerate(choices):
					hdr_cells[i].text = choice[0]
				table.style = 'TableGrid'

		

	document.add_page_break()
	if not os.path.exists(os.path.join(settings.BASE_DIR, 'files', 'forms')):
		os.makedirs(os.path.join(settings.BASE_DIR, 'files', 'forms'))
	path = os.path.join(settings.BASE_DIR, 'files', 'forms', '%s.docx' % str(uuid4()))

	document.save(path)
	return path
예제 #5
0
 def _save_results(filename, abstracts):
     document = Document()
     for title, content in abstracts:
         document.add_heading(title, level=0)
         for p in content.split("\r\n"):
             document.add_paragraph(p)
         document.add_page_break()
     document.save("./result/" + filename)
예제 #6
0
파일: prograph.py 프로젝트: lucawen/Clima
def processa(_col_pontos, _col_campanha, _col_parametro,  _idleg, _idclasse):

    document = Document('/home/wbeirigo/Clima/weather/proj/matriz.docx')

    URL_PHANTOM = 'http://10.3.0.29:3003'
    headers ={ 'Content-Type': 'application/json', '-X POST':'' }
    indice = 0


    section = document.add_section()
    section.orientation = WD_ORIENT.LANDSCAPE
    indice += 1
    document.add_paragraph('  ', style='Normal')
    document.add_paragraph('  ', style='Normal')
    document.add_heading(u'Quadro 6.{0} - - Resultados do monitoramento da qualidade da água'.format(indice, ''), level=2)
    #geraTabela(document, _col_pontos, _col_campanha, _idleg, _idclasse)
    document.add_paragraph('  ', style='Normal')
    section = document.add_section()
    section.orientation = WD_ORIENT.PORTRAIT
    for parametro  in _col_parametro:

        """ Não processa parametros Data e Profundidade"""
        if parametro in (798,840):
            continue

        saida = geraGraphico(_col_pontos, _col_campanha, parametro, _idleg, _idclasse)
        if not saida:
            continue
        r = requests.post(URL_PHANTOM, data=saida, headers=headers)
        png_recovered = base64.decodestring(r.content)
        path = "/tmp/{0}.png".format(int(time.time()*1000))
        f = open(path, "w")
        f.write(png_recovered)
        f.close()

        indice += 1
        obj_param = Param.objects.get(pk=parametro)
        nome = obj_param.nome
        texto = obj_param.texto
        document.add_heading(u'6.{0} - {1}'.format(indice, nome), level=3)
        document.add_paragraph('  ', style='Normal')
        document.add_paragraph(texto, style='Normal')
        document.add_paragraph('  ', style='Normal')
        document.add_paragraph('  ', style='Normal')
        document.add_paragraph(u'Figura 6.{0} -Resultados obtidos para o parâmetro {1}'.format(indice, nome), style='f')
        document.add_picture(path, width=Inches(5.2))
        document.add_paragraph('  ', style='Normal')
        last_paragraph = document.paragraphs[-1]
        last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
        document.add_page_break()
        os.remove(path)
    caminho = '/media/projeto_cemig/01_SOFTWARE/rel/'
    path = caminho + "{0}.docx".format(int(time.time()*1000))
    document.save(path)
    return path
예제 #7
0
def main():
    reload(sys)
    sys.setdefaultencoding('utf-8')
    
    # 创建文档对象
    document = Document()
    
    # 设置文档标题,中文要用unicode字符串
    document.add_heading(u'我的一个新文档',0)
    
    # 往文档中添加段落
    p = document.add_paragraph('This is a paragraph having some ')
    p.add_run('bold ').bold = True
    p.add_run('and some ')
    p.add_run('italic.').italic = True
    
    # 添加一级标题
    document.add_heading(u'一级标题, level = 1',level = 1)
    document.add_paragraph('Intense quote',style = 'IntenseQuote')
    
    # 添加无序列表
    document.add_paragraph('first item in unordered list',style = 'ListBullet')
    
    # 添加有序列表
    document.add_paragraph('first item in ordered list',style = 'ListNumber')
    document.add_paragraph('second item in ordered list',style = 'ListNumber')
    document.add_paragraph('third item in ordered list',style = 'ListNumber')
    
    # 添加图片,并指定宽度
    document.add_picture('e:/docs/pic.png',width = Inches(1.25))
    
    # 添加表格: 1行3列
    table = document.add_table(rows = 1,cols = 3)
    # 获取第一行的单元格列表对象
    hdr_cells = table.rows[0].cells
    # 为每一个单元格赋值
    # 注:值都要为字符串类型
    hdr_cells[0].text = 'Name'
    hdr_cells[1].text = 'Age'
    hdr_cells[2].text = 'Tel'
    # 为表格添加一行
    new_cells = table.add_row().cells
    new_cells[0].text = 'Tom'
    new_cells[1].text = '19'
    new_cells[2].text = '12345678'
    
    # 添加分页符
    document.add_page_break()
    
    # 往新的一页中添加段落
    p = document.add_paragraph('This is a paragraph in new page.')
    
    # 保存文档
    document.save('e:/docs/demo1.docx')
예제 #8
0
def make_entry(res):
    # pull out the target notebook date from the regex
    date = dateutil.parser.parse(res.match.group('date'))
    logging.debug("new notebook target date: %s", date)

    # query the database for announcements from the specified date
    # TODO: build a new brain api and refactor?
    announcements = res.robot.brain.db.search((where('plugin') == 'notebook')
        & (where('type') == 'announcement')
        & (where('date') == date.isoformat())
        )

    logging.debug("announcements are %s", announcements)

    # if there actually _are_ announcements for that date
    if announcements != []:
        document = None
        if res.robot.config['plugin_config']['notebook']['append']:
            document = Document(res.robot.config['plugin_config']['notebook']['file'])
        else:
            # create a new docx document object
            document = Document()

        # fill in a bunch of boilerplate
        document.add_page_break()
        document.add_heading('{date}, the BEC'.format(date=date.strftime('%m/%d/%Y')), level=1)
        document.add_heading('Announcements:', level=2)

        # pull out a list of all the users that had announced
        users = set(map(lambda a: a['user'], announcements))

        logging.debug("users are %s", users)

        # for each user who has announced
        for user in sorted(users):
            # get their real name
            real_name = res.robot.slack_client.server.users.find(user).real_name
            logging.debug("announcing user %s is %s", user, real_name)
            # create a new heading for them
            document.add_paragraph("{}:".format(real_name))
            # for every one of their posts
            for announcement in announcements:
                if announcement['user'] == user:
                    # create a bullet-point for that announcement
                    document.add_paragraph("{}".format(announcement['announcement']),
                                           style='ListBullet')

        # TODO: onedrive
        document.save(res.robot.config['plugin_config']['notebook']['file'])
    else:
        # let the user know that that meeting date doesn't exist
        res.reply(res.msg.user, "No announcements for date {}".format(date.strftime('%m/%d/%Y')))
예제 #9
0
  def write(self,data):
    """ Take a list of row and save into a file """
    out = None
    if(self.otype=='pkl'):
      out = pickle.dumps(data)    
      with open(self.ofull_name,'wb') as f:
        f.write(out)
  
    if(self.otype=='xls'):
      wb = Workbook()
      ws = wb.active
      ws.title = "range names"
      for col_idx in range(0, len(data)):
        col = get_column_letter(col_idx+1)
        for row in range(0, len(data[col_idx])):
          ws.cell('%s%s'%(col, row+1)).value = data[col_idx][row]
      ws = wb.create_sheet()
      ws.title = 'Pi'
      ws['F5'] = 3.14
      wb.save(filename = self.ofull_name)
      
    if(self.otype=='docx'):
      document = Document()
      document.add_heading(self.ofull_name, 0)

      table = document.add_table(rows=0, cols=len(data))
      #hdr_cells = table.rows[0].cells
      #hdr_cells[0].text = 'Qty'
      #hdr_cells[1].text = 'Id'
      #hdr_cells[2].text = 'Desc'
      for row in data:
          row_cells = table.add_row().cells
          for col_idx in range(len(row)):
            row_cells[col_idx].text = str(row[col_idx])
      document.add_page_break()
      document.save(self.ofull_name)

    if(self.otype=='xls'):
      pass
    if(self.otype=='xls'):
      pass
 
    print 'Success:Write'




#test code..
#d =[['a','b','c','d'],['a','b','c','d'],['a','b','c','d'],['a','b','c','d']]
#b = BackUp('hello','docx')
#b.write(d)
#print b.read()
예제 #10
0
def create_word_document():
    """Creates a word document containing job data"""

    document = Document()

    style=document.styles['Normal']
    style.font.name = 'Calibri'
    style.font.size = Pt(12)


    def add_line(label, value):
        """Adds the paragraph with format of 'label: value[bolded]'"""
        para = document.add_paragraph()
        para_label = para.add_run(label + ": ")
        para_value = para.add_run(value)
        para_value.bold = True

    jobs = db.get_csv_json_text_data()

    for job in jobs:
        title = document.add_paragraph(job[1], style='Title')
        title.alignment = 1

        employer_name = document.add_heading(job[2], level=1)
        employer_name.alignment = 1

        add_line('Location', job[4])
        add_line('Level', job[6])
        add_line('Number of Openings', job[5])
        add_line('Discipline', job[7])
        add_line('Job Id', job[0])


        if (len(job[10]) > 10): #show Comments header only if the job contains comments
            document.add_heading('Comments', level=2)
            document.add_paragraph(job[10])

        # document.add_paragraph('\n\n\n\n\n\n\n')

        document.add_heading('Summary', level=2)
        #every time a <br /> occurs, add a linebreak to the current document
        print('The type of job[11] is: ' + str(type(job[11])))
        summary = job[11].replace('<br />', '\n').replace('&#039;', "'").replace('&nbsp;', ' ')
        document.add_paragraph(summary)

        document.add_page_break()

    document.save('jobs_EZSearch.docx')
예제 #11
0
    def handle(self, *args, **options):

        courses = Course.objects.filter(status='published')
        if not courses.exists():
            print "There's no published courses to extract"
            return

        dir_name = 'extract_forum'
        if not os.path.exists(dir_name):
            os.makedirs(dir_name)

        print "Generating files for %d courses"
        for course in courses:
            doc = Document()
            doc.add_heading(course.name, level=1)
            doc.add_paragraph()
            for question in course.question_set.filter(hidden=False).order_by('timestamp'):

                user_name = question.user.get_full_name()

                if not user_name:
                    user_name = question.user.username

                p = doc.add_paragraph()
                p.add_run(question.title).bold = True
                p.add_run(' (por ')
                p.add_run(user_name).italic = True
                p.add_run(')')

                p = doc.add_paragraph(question.text)

                for answer in question.answers.order_by('timestamp'):
                    user_name = answer.user.get_full_name()
                    if not user_name:
                        user_name = answer.user.username
                    p = doc.add_paragraph('R: ' + answer.text)
                    p = doc.add_paragraph()
                    p.add_run('por ' + user_name).italic = True

                doc.add_paragraph('_' * 105)
                doc.add_paragraph()

            file_name = os.path.join(dir_name, slugify(course.name) + datetime.datetime.now().strftime('_%Y%m%d%I%M.docx'))

            doc.add_page_break()
            print file_name
            doc.save(file_name)
예제 #12
0
def createDummyDocument():
	document = Document(resource_path(os.path.join("assets","default.docx")))

	document.add_heading('Document Title', 0)

	p = document.add_paragraph('A plain paragraph having some ')
	p.add_run('bold').bold = True
	p.add_run(' and some ')
	p.add_run('italic.').italic = True

	document.add_heading('Heading, level 1', level=1)
	document.add_paragraph('Intense quote', style='IntenseQuote')

	document.add_paragraph(
	    'first item in unordered list', style='ListBullet'
	)
	document.add_paragraph(
	    'first item in ordered list', style='ListNumber'
	)

	# document.add_picture('monty-truth.png', width=Inches(1.25))

	table = document.add_table(rows=1, cols=0, style='LightShading-Accent1')
	column0 = table.add_column()
	column0.width = 5000000
	column1 = table.add_column()
	column2 = table.add_column()
	# print table.columns.cells
	table.columns.width = 200000

	hdr_cells = table.rows[0].cells
	hdr_cells[0].text = 'Qty'
	hdr_cells[1].text = 'Id'
	hdr_cells[2].text = 'Desc'

	tableData = [["5", "Apples", "yummy"], ["6", "Oranges", "they're orange"]]

	for row in tableData:
		row_cells = table.add_row().cells
		row_cells[0].text = row[0]
		row_cells[1].text = row[1]
		row_cells[2].text = row[2]


	document.add_page_break()

	document.save('demo.docx')
예제 #13
0
    def __init__(self, data, fname, text=True):
        self.data = data
        filename = constants.fileloc + fname + \
                   time.asctime().replace(":", "_").replace(" ", "_").replace("%", "_") + ".docx"
        from docx import Document
        document = Document()
        print self.data
        for page in self.data:
            # try:
            title = page[0]
            data = page[1]
            h = document.add_heading(title, 0)
            document.add_paragraph(data)
            document.add_page_break()
            # except:
            #     pass

        document.save(filename)
예제 #14
0
def combine_docx(file_names, file_name_out):
    combined_document = Document(file_names[0])
    count, number_of_files = 0, len(file_names)
    for file in file_names[1:]:
        if file == "pagebreak":
            combined_document.add_page_break()
        else:    
            sub_doc = Document(file)
            for para in sub_doc.paragraphs:
                pnew = combined_document.add_paragraph(style=para.style)
                docx_copy_para_format_from(pnew, para)
                runs = para.runs
                for run in runs:
                    rnew = pnew.add_run(text=run.text, style=run.style)
                    docx_copy_run_style_from(rnew, run)

    combined_document.save(file_name_out)
    return {"file":file_name_out}
def report():
	document = Document()
	table = document.add_table(rows=1, cols=7)
	hdr_cells = table.rows[0].cells
	hdr_cells[0].text = 'Hote'
	hdr_cells[1].text = 'Systeme dexploitation'
	hdr_cells[2].text = 'Port'
	hdr_cells[3].text = 'Service'
	hdr_cells[4].text = 'Logiciel'
	hdr_cells[5].text = 'Version'
	hdr_cells[6].text = 'Information'


	table2 = document.add_table(rows=1, cols=1)
	#print data
	count = 0
	for i in range(0,len(data),1):
		line = data.pop()
		#print line
		row_cells = table.add_row().cells
		row_cells[0].text = line[0]
		row_cells[1].text = line[1]

		count2 = 0
		for i in range(len(line[2])):

			if count2 > 0:
				row_cells = table.add_row().cells
				row_cells[0].text = ""
				row_cells[1].text = ""
			row_cells[2].text = line[2][count2]
			row_cells[3].text = line[3][count2]
			row_cells[4].text = line[4][count2]
			row_cells[5].text = line[5][count2]
			row_cells[6].text = line[6][count2]
			count2+=1

	if tablestyle:
		table.style=tablestyle

	document.add_page_break()

	document.save(o)
	print "[*] Jobs done\n"
예제 #16
0
	def down(self):
		reqHeader = config.reqHeaderBDWK
		reqHeader['Referer'] = self.URL
		i = 1
		docFileName = self.fileDir + self.WkInfo['title'] + '.' + self.WkInfo['docType']
		document = Document() # 创建doc(x)文档
		while i <= self.WkInfo['totalPageNum']:
			jsonUrl = DownDocx.geturl(self.WkInfo['htmlUrls']['json'], i)
			if len(jsonUrl) == 0:
				logger.error('下载文档失败,查找URL失败!')
				return False
			jsonUrl = jsonUrl.replace('\\', '')
			jsonUrl = jsonUrl.replace(' ', '%20')
			req = urllib2.Request(jsonUrl, headers=reqHeader)
			res = urllib2.urlopen(req)
			res = res.read()
			jsonRet = res[res.find('(')+1 : res.rfind(')')]
			logger.info('打印一下,获取json数据内容为 ' + jsonRet)
			jsonRet = json.loads(jsonRet)
			# 再处理获取的页面内容
			first = 0
			for item in jsonRet['body']:
				if item['t'] != 'word':
					continue
				#if first == 0 or (item['ps'] and item['ps']['_enter'] == 1):
				if first == 0 or (item['ps'] and json_get(item, ['ps', '_enter'], '0') == 1):
					first = 1
					pg = document.add_paragraph()
				#if item['ps'] and item['ps']['_enter'] == 1:
				if item['ps'] and json_get(item, ['ps', '_enter'], '0') == 1:
					continue
				run = pg.add_run(item['c'])
				# 添加格式;分析不出来,就统一宋体、五号
				run.font.name = u'宋体'
				run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
				run.font.size = Pt(10.5)
			# 下一页
			if i < self.WkInfo['totalPageNum']:
				document.add_page_break()
				print 'Page' + str(i)
				#time.sleep(1)
			i += 1
		document.save(docFileName)
		return True
예제 #17
0
파일: hawkDOCX.py 프로젝트: ddfelts/hawk2.0
class hawkDOCX():

    def __init__(self,name,template,hawk):
        self.doc = Document(template)
        self.secs = self.doc.sections
        self.name = name
        self.hlib = hawklib(hawk)
        self.cur = None

    def addPara(self,data):
        self.cur = self.doc.add_paragraph(data)

    def addHead(self,data):
        self.doc.add_heading(data,level=1)

    def addPageBreak(self):
        self.doc.add_page_break()

    def addImage(self,image,w=None):
        if w == None:
            self.doc.add_picture(image)
        else:
            self.doc.add_picture(image,width=Inches(w))

    def addTable(self,data,nkeys=None):
        if not nkeys:
            keys = self.hlib.getKeys(data)
        else:
            keys = nkeys
        table = self.doc.add_table(rows=1,cols=len(keys))
        row = table.rows[0]
        for i in range(len(keys)):
            row.cells[i].text = str(keys[i])
        for x in data:
            nrow = table.add_row().cells
            for b in range(len(keys)):
                if keys[b] not in x:
                    outb = None
                else:
                    outb = x[keys[b]]
                nrow[b].text = str(outb)

    def saveDoc(self):
        self.doc.save(self.name)
예제 #18
0
def generate_random_docx(filename, paraph_size=30):
    document = Document()

    size = random.randint(5, paraph_size)
    document.add_heading(generate_random_string(size), 0)

    size = random.randint(5, paraph_size)
    p = document.add_paragraph(
                               generate_random_string(size))
    p.add_run('bold').bold = True
    p.add_run(' and some ')
    p.add_run('italic.').italic = True

    size = random.randint(5, paraph_size)
    document.add_heading(generate_random_string(size), level=1)
    size = random.randint(5, paraph_size)
    document.add_paragraph(generate_random_string(size), style='IntenseQuote')

    for _ in range(random.randint(1, 10)):
        size = random.randint(5, paraph_size)
        document.add_paragraph(
                        generate_random_string(size), style='ListBullet')

    for _ in range(random.randint(1, 10)):
        size = random.randint(5, paraph_size)
        document.add_paragraph(
                        generate_random_string(size), style='ListNumber')

    table = document.add_table(rows=1, cols=3)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = 'Qty'
    hdr_cells[1].text = 'Id'
    hdr_cells[2].text = 'Desc'
    for i in range(random.randint(1, 10)):
        row_cells = table.add_row().cells
        row_cells[0].text = str(i)
        row_cells[1].text = generate_random_string(8)
        row_cells[2].text = generate_random_string(30)

    document.add_page_break()

    document.save(filename)
예제 #19
0
파일: doc.py 프로젝트: buret/pylmflib
def doc_write(object, filename, introduction=None, lmf2doc=lmf_to_doc, items=lambda lexical_entry: lexical_entry.get_lexeme(), sort_order=None, paradigms=False, reverse=False):
    """! @brief Write a document file.
    @param object The LMF instance to convert into document output format.
    @param filename The name of the document file to write with full path, for instance 'user/output.doc'.
    @param introduction The name of the text file with full path containing the introduction of the document, for instance 'user/config/introduction.txt'. Default value is None.
    @param lmf2doc A function giving the mapping from LMF representation information that must be written to docx commands, in a defined order. Default value is 'lmf_to_doc' function defined in 'pylmflib/config/doc.py'. Please refer to it as an example.
    @param items Lambda function giving the item to sort. Default value is 'lambda lexical_entry: lexical_entry.get_lexeme()', which means that the items to sort are lexemes.
    @param sort_order Python list. Default value is 'None', which means that the document output is alphabetically ordered.
    @param paradigms A boolean value to introduce paradigms in document or not.
    @param reverse A boolean value to set if a reverse dictionary is wanted.
    """
    import string
    if sort_order is None:
        # Lowercase and uppercase letters must have the same rank
        sort_order = dict([(c, ord(c)) for c in string.lowercase])
        up = dict([(c, ord(c) + 32) for c in string.uppercase])
        sort_order.update(up)
        sort_order.update({'':0, ' ':0})
    document = Document()
    # Adjust margins to 1 cm
    section = document.sections[0]
    section.top_margin = Cm(1)
    section.bottom_margin = Cm(1)
    section.left_margin = Cm(1)
    section.right_margin = Cm(1)
    # Parse LMF values
    if object.__class__.__name__ == "LexicalResource":
        for lexicon in object.get_lexicons():
            # Document title
            document.add_heading(lexicon.get_id(), 0)
            # Plain paragraph
            document.add_paragraph(lexicon.get_label())
            # Page break
            document.add_page_break()
            # Introduction
            if introduction is not None:
                document.add_paragraph(file_read(introduction))
            # Text body
            lmf2doc(lexicon, document, items, sort_order, paradigms, reverse)
    else:
        raise OutputError(object, "Object to write must be a Lexical Resource.")
    document.save(filename)
예제 #20
0
def _make_docx(result, file_object):
    document = Document()
    for card in result['Records']:
        p = document.add_paragraph(u'ИНФОРМАЦИОННАЯ КАРТОЧКА')
        p.alignment = 1

        p = document.add_paragraph(u'встреч растений и грибов, занесенных в Красную книгу')
        p.alignment = 1

        p = document.add_paragraph(u'Ханты-Мансийского автономного округа')
        p.alignment = 1

        p = document.add_paragraph(card['taxon__name'])
        p.alignment = 1

        p = document.add_paragraph(card['taxon__russian_name'])
        p.alignment = 1

        p = document.add_paragraph(u'№ ' + str(card['cards__id']))
        p.alignment = 1

        card_for_rendering = DictionaryMissingValues(card)
        _add_paragraph(document, u'Место находки: ', card_for_rendering.get_value('cards__location', u'не описано'))
        _add_paragraph(document, u'Долгота: ', str(card['cards__lon']) if card['cards__lon'] else u'информации нет')
        _add_paragraph(document, u'Широта: ', str(card['cards__lat']) if card['cards__lat'] else u'информации нет')
        _add_paragraph(document, u'Местообитание: ', card['cards__habitat'] if card['cards__habitat'] else u'информации нет')
        _add_paragraph(document, u'Антропогенная нагрузка: ', card['cards__anthr_press'] if card['cards__anthr_press'] else u'информации нет')
        _add_paragraph(document, u'Лимитирующие факторы: ', card['cards__limit_fact'] if card['cards__limit_fact'] else u'информации нет')
        _add_paragraph(document, u'Меры защиты: ', card['cards__protection'] if card['cards__protection'] else u'информации нет')
        _add_paragraph(document, u'Фаза жизненного цикла: ', str(card['cards__pheno']) if card['cards__pheno'] else u'информации нет')
        _add_paragraph(document, u'Количество: ', str(card['cards__quantity']) if card['cards__quantity'] else u'информации нет')
        _add_paragraph(document, u'Площадь популяции: ', card['cards__area'] if card['cards__area'] else u'информации нет')
        _add_paragraph(document, u'Примечания: ', card['cards__notes'] if card['cards__notes'] else u'примечаний нет')
        _add_paragraph(document, u'Музейные образцы: ', card['cards__museum'] if card['cards__museum'] else u'информации нет')
        _add_paragraph(document, u'Источник информации: ', card['cards__publications'] if card['cards__publications'] else u'информации нет')
        _add_paragraph(document, u'Наблюдал: ', card_for_rendering.get_value('observer__name', u'информации нет'))

        document.add_page_break()

    document.save(file_object.name)
예제 #21
0
파일: pydocx.py 프로젝트: bianle/7w523
def genDocx(self):
	document = Document()
	document.add_heading(u'2015全年工作日报', 0)

	document.add_heading(u'第38周(09月14日-09月18日)', level=1)
	document.add_heading(u'09月14日', level=2)
	document.add_paragraph(
		'xxx', style='ListNumber'
	)
	document.add_paragraph(
		'yyy', style='ListNumber'
	)
	document.add_paragraph(
		'zzz', style='ListNumber'
	)




	document.add_page_break()

	document.save('demo.docx')
예제 #22
0
파일: xq_new.py 프로젝트: HiRoad/hello
def generate_docx():
    #
    check_db()
    global DB_CURSOR
    global DB_INSTANCE
    #
    document = Document()

    #
    DB_CURSOR.execute(' select pid, title, created_at, userid, username, content from xq_fav ')
    lists = DB_CURSOR.fetchall()

    for vals in lists:
        # title
        document.add_heading( '%s @%s' % (vals[1], vals[4]), 0 )
        # content
        generate_xq_content( document, vals[5] )
        # next page
        document.add_page_break()
        #
    #
    doc_file = 'D:/HiRoad_XQFav_%s.docx' % datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
    document.save(doc_file)
예제 #23
0
	def export(self, filename):
		from docx import Document
		if filename.split('.')[-1] != '.docx':
			filename += '.docx'
		document = Document()
		h = document.add_heading(self.title, 0)
		h.add_run('bold').bold = True

		if self.text:
			for p in self.data:
				document.add_paragraph(p)
		else:
			table = document.add_table(rows=len(self.data), cols=len(self.data[0]))
			r, c = -1, -1
			for row in self.data:
				r += 1
				c = 0
				for col in row:
					hdr_cells = table.rows[0].cells
					hdr_cells[c].text = col
					c += 1

		document.add_page_break()
		document.save(filename)
예제 #24
0
파일: docgen.py 프로젝트: fpt/webtoys
class DocWriter(BaseWriter):
    """Factory"""

    def __init__(self, fp):
        self.fp = fp
        self.document = Document()

    def add_heading(self, str, level=None):
        self.document.add_heading(str, level=level)

    def add_paragraph(self, str):
        self.document.add_paragraph(str)

    def add_image(self, img):
        img_bytes = BytesIO()
        img.save(img_bytes, format="png")
        img_bytes.seek(0)
        self.document.add_picture(img_bytes)

    def add_page_break(self):
        self.document.add_page_break()

    def close(self):
        self.document.save(self.fp)
예제 #25
0
파일: otc.py 프로젝트: Dmitrijjj/asp
def create_otc_document(doc_json, mess_id):
    arr = list()
    document = Document()
    res = json.loads(doc_json)

    document.add_heading(u'Отчет о распространении сообщения в соцсетях (по репостам)', 0)
    document.add_paragraph(res["1"]["author"] + " " +res["1"]["date"])
    document.add_paragraph(res["1"]["text"])
    document.add_page_break() #Закончен первый лист - заголовок, текст

    #Гистограммы сюда
    document.add_page_break() #Закончен второй лист лист - гистограммы

    while res:
        key, value = res.popitem()
        arr.append(value)
    arr = sorted(arr, key=lambda k: k['date'], reverse=True)

    table = document.add_table(rows=1, cols=6)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = u'Дата'
    hdr_cells[1].text = u'Автор'
    hdr_cells[2].text = u'Лайки'
    hdr_cells[3].text = u'Репосты'
    hdr_cells[4].text = u'Комментарии'
    hdr_cells[5].text = u'Оригинал'
    while arr:
        elem = arr.pop()
        row_cells = table.add_row().cells
        row_cells[0].text = unicode(elem["date"])
        row_cells[1].text = unicode(elem["author"])
        row_cells[2].text = unicode(elem["likes"])
        row_cells[3].text = unicode(elem["comments"])
        row_cells[4].text = unicode(elem["reposts"])
        row_cells[5].text = unicode(elem["original"])
    document.add_page_break() #Закончен третий  лист - таблица
    document.save("demo.docx")
def llenar_inter_silici(nombre_archivo):
    general = pd.read_csv("./archivos/current_general.csv",
                          sep=";",
                          encoding="latin")
    conteo = pd.read_csv("./archivos/Conteo_siliciclasticas.csv",
                         sep=";",
                         encoding="latin")
    igm = str(general.iloc[0]["igm"])
    if igm == nan: igm = "IGM"
    redondez, esfericidad = redondez_p()
    promedios_grano, redond_p, esfer_p = promedios_silic()
    soportes = soporte_g()
    t_contactos = contactos_sed()
    datos_comp, prom_tam, redon_com, esfer_com = datos_silic()
    porcent_tam, av_size = simplificacion_conteo()
    archivo = Document(nombre_archivo)

    archivo.add_page_break()
    archivo.add_paragraph()
    archivo.add_heading("DESCRIPCIÓN MICROSCÓPICA - " + igm)
    archivo.add_paragraph()
    archivo.add_heading("DESCRIPCIÓN TEXTURAL", 2)
    archivo.add_paragraph()
    lista = [
        'HOMOGENEIDAD DE LA ROCA:', 'TAMAÑO DE GRANO PROMEDIO: ' + av_size,
        'RANGO DE TAMAÑOS:', 'SELECCIÓN:', 'REDONDEZ PROMEDIO: ' + redondez,
        'ESFERICIDAD PROMEDIO: ' + esfericidad, 'MADUREZ TEXTURAL:'
    ]
    for i in lista:
        p1 = archivo.add_paragraph()
        r1 = p1.add_run(i)
        r1.italic = True
        r1.bold = True
        p1.add_run(" ")
    p1 = archivo.add_paragraph()
    list = [
        'GRAVA: ' + porcent_tam["GRAVA"] + ' (%)',
        'Tamaño promedio: ' + promedios_grano[0] + ' mm	 Redondez: ' +
        redond_p[0] + ' Esfericidad: ' + esfer_p[0],
        'ARENA: ' + porcent_tam["ARENA"] + ' (%)',
        'Tamaño promedio: ' + promedios_grano[1] + ' mm	 Redondez: ' +
        redond_p[1] + ' Esfericidad: ' + esfer_p[1],
        'LODO: ' + porcent_tam["LODO"] + ' (%)', 'Arcilla: ' +
        porcent_tam["ARCILLA"] + ' % Tamaño promedio fracción arcilla: ' +
        promedios_grano[4] + ' mm \nLimo: ' + porcent_tam["LIMO"] + ' %' +
        'Tamaño promedio fracción limo: ' + promedios_grano[3] + ' mm ',
        'CONTACTO ENTRE GRANOS:', 'Flotante: ' + t_contactos["Flotante"] +
        ' % Tangencial: ' + t_contactos["Tangencial"] + ' %\nLongitudinal: ' +
        t_contactos["Longitudinal"] + ' % Cóncavo-convexo: ' +
        t_contactos["Concavo-Convexo"] + ' %\nSuturado: ' +
        t_contactos["Suturado"] + ' %', 'SOPORTE DE LA ROCA:',
        'Granos terrígenos-aloquímicos: ' + soportes["grano"] +
        ' % Minerales arcillosos: ' + soportes["arcilloso"] + ' %'
    ]

    contador = 0
    for i in list:  #los datos de grava y tamaño y lo demás de la list se pueden llenar con info de interfaz
        if contador % 2 == 0:
            p1 = archivo.add_paragraph()
            r1 = p1.add_run(i)
            r1.italic = True
            r1.bold = True
            p1.add_run(" ")
        else:
            p1 = archivo.add_paragraph()
            r1 = p1.add_run(i)
            p1.add_run(" ")
        archivo.add_paragraph()
        contador = contador + 1
    p1 = archivo.add_paragraph()
    r1 = p1.add_run("POROSIDAD:")
    r1.bold = True
    r1.underline = True
    p1.add_run(" " + soportes["Porosidad"] + ' %    Primaria: ' +
               soportes["Primaria"] + ' %    Secundaria: ' +
               soportes["Secundaria"] + ' % \nTipo(s), origen y descripción')
    archivo.add_paragraph()
    p2 = archivo.add_paragraph()
    r1 = p2.add_run("ESTRUCTURAS:")
    r1.bold = True
    r1.underline = True
    archivo.add_paragraph()
    archivo.add_heading('CLASIFICACIÓN TEXTURAL')
    archivo.add_paragraph()
    clas_roc = archivo.add_paragraph()
    run = clas_roc.add_run("NOMBRE TEXTURAL ")
    run.bold = True
    run.underline = True
    r2 = clas_roc.add_run("(Folk, 1954):")
    r2.underline = True
    archivo.add_paragraph('(Grava + Arena + Lodo = 100%)')
    archivo.add_page_break()
    archivo.add_paragraph()
    archivo.add_heading("DESCRIPCIÓN COMPOSICIONAL - " + igm)
    archivo.add_paragraph()
    archivo.add_heading("TERRIGENOS: " + datos_comp["Terrigenos"] + ' (%)', 3)
    archivo.add_paragraph()

    list2 = [
        'Cuarzo: ' + datos_comp["Cuarzo"] + ' (%)', 'Monocristalino: ' +
        datos_comp["Cuarzo mono"] + ' (%) Tamaño promedio: ' +
        prom_tam["Cuarzo mono"] + ' mm Esfericidad: ' +
        esfer_com["Cuarzo mono"] + ' Redondez: ' + redon_com["Cuarzo mono"] +
        '\nPolicristalino: ' + datos_comp["Cuarzo poli"] +
        ' %	Tamaño promedio: ' + prom_tam["Cuarzo poli"] +
        ' mm Esfericidad: ' + esfer_com["Cuarzo poli"] + ' Redondez: ' +
        redon_com["Cuarzo poli"] + '\nObservaciones:____ ',
        'Chert: ' + datos_comp["Chert"] + ' %',
        'Tamaño promedio: ' + prom_tam["Chert"] + ' mm Esfericidad: ' +
        esfer_com["Chert"] + ' Redondez: ' + redon_com["Chert"],
        'Feldespato: ' + datos_comp["Feldespato"] + ' %',
        'Potásico: ' + datos_comp["Feldespato K"] + ' % Tamaño promedio: ' +
        prom_tam["Feldespato K"] + ' mm	Esfericidad: ' +
        esfer_com["Feldespato K"] + ' Redondez: ' + redon_com["Feldespato K"] +
        '\nSódico-Cálcico: ' + datos_comp["Feldespato Na - Ca"] +
        ' % Tamaño promedio: ' + prom_tam["Feldespato Na - Ca"] +
        ' mm Esfericidad: ' + esfer_com["Feldespato Na - Ca"] + ' Redondez: ' +
        redon_com["Feldespato Na - Ca"]
    ]
    contador = 0
    for i in list2:  #los datos de grava y tamaño y lo demás de la list se pueden llenar con info de interfaz
        if contador % 2 == 0:
            p1 = archivo.add_paragraph()
            r1 = p1.add_run(i)
            r1.italic = True
            r1.bold = True
            p1.add_run(" ")
        else:
            p1 = archivo.add_paragraph()
            r1 = p1.add_run(i)
            p1.add_run(" ")
        archivo.add_paragraph()
        contador = contador + 1
    list3 = [
        'Micas: ' + datos_comp["Micas"] + ' %', 'Descripción ______',
        'Minerales Arcillosos: ' + datos_comp["Min. arcillosos"] + ' %',
        ' Descripción_____',
        'Granos Aloquímicos: ' + datos_comp["Granos aloq."] + ' %',
        'Descripción_____',
        'Otros Terrígenos: ' + datos_comp["Otros terrigenos"] + ' %',
        'Descripción_____', 'Opacos: ' + datos_comp["Opacos"] + ' %',
        'Descripción_______'
    ]
    contador = 0
    for i in list3:  #los datos de grava y tamaño y lo demás de la list se pueden llenar con info de interfaz
        if contador % 2 == 0:
            p1 = archivo.add_paragraph(False)
            r1 = p1.add_run(i)
            r1.italic = True
            r1.bold = True
            p1.add_run(" ")
        else:
            p1 = archivo.add_paragraph()
            r1 = p1.add_run(i)
            p1.add_run(" ")
        archivo.add_paragraph()
        contador = contador + 1
    archivo.add_paragraph()
    archivo.add_heading(
        'LÍTICOS (Ígneos, Metamórficos, Sedimentarios): ' +
        datos_comp["Liticos"] + ' (%)', 3)
    archivo.add_paragraph()
    list4 = [
        'Líticos Metamórficos: ' + datos_comp["Metamorficos"] + ' %',
        'Tamaño promedio: ' + prom_tam["Metamorficos"] + ' mm	Esfericidad: ' +
        esfer_com["Metamorficos"] + ' Redondez: ' + redon_com["Metamorficos"],
        'Líticos Volcánicos: ' + datos_comp["Volcanicos"] + ' %',
        'Tamaño promedio: ' + prom_tam["Volcanicos"] + ' mm	Esfericidad: ' +
        esfer_com["Volcanicos"] + ' Redondez: ' + redon_com["Volcanicos"],
        'Líticos Plutónicos: ' + datos_comp["Plutonicos"] + ' %',
        'Tamaño promedio: ' + prom_tam["Plutonicos"] + ' mm	Esfericidad: ' +
        esfer_com["Plutonicos"] + ' Redondez: ' + redon_com["Plutonicos"],
        'Líticos Sedimentarios: ' + datos_comp["Sedimentarios"] + ' %',
        'Tamaño promedio: ' + prom_tam["Sedimentarios"] + ' mm	Esfericidad: ' +
        esfer_com["Sedimentarios"] + ' Redondez: ' +
        redon_com["Sedimentarios"] + '\nObservaciones:_____',
        'Materia Orgánica: ' + datos_comp["Materia org."] + ' %',
        'Tipo(s):_____', 'Cemento: ' + datos_comp["Cemento"] + ' %',
        'Tipo(s):' + '\nTamaño cristalino: ' + prom_tam["Cemento"] + ' mm',
        'Otros Ortoquímicos: ' + datos_comp["Otros ortoq."] + ' %',
        'Tipo(s)(incluye minerales autigénicos):_____'
        '\nTamaño:____mm'
    ]
    contador = 0
    for i in list4:
        if contador % 2 == 0:
            p1 = archivo.add_paragraph()
            r1 = p1.add_run(i)
            r1.italic = True
            r1.bold = True
            p1.add_run(" ")
        else:
            p1 = archivo.add_paragraph()
            r1 = p1.add_run(i)
            p1.add_run(" ")
        archivo.add_paragraph()
        contador = contador + 1
    archivo.add_paragraph()
    archivo.add_heading('CLASIFICACIÓN COMPOSICIONAL')
    archivo.add_paragraph()
    clas_roc = archivo.add_paragraph()
    run = clas_roc.add_run("NOMBRE COMPOSICIONAL ")
    run.bold = True
    run.underline = True
    r2 = clas_roc.add_run("(Folk, 1954):")
    r2.underline = True
    archivo.add_paragraph()
    archivo.add_heading('DIAGÉNESIS', 2)
    z1 = archivo.add_paragraph('Autigénesis:')
    z2 = archivo.add_paragraph('Recristalización:')
    z1.bold = True
    z2.bold = True
    archivo.save(nombre_archivo)
예제 #27
0
def genPack(contact,fn):
    global document
    document = Document(fn)
    tbl=document.tables[0]
    changeGrid2(tbl,0,1,contact.yonghu)
    changeGrid2(tbl,1,1,contact.yiqixinghao)
    changeGrid2(tbl,2,1,contact.yiqibh)
    changeGrid2(tbl,3,1,contact.baoxiang)
    changeGrid2(tbl,4,1,contact.shenhe)
    changeGrid2(tbl,5,1,myformat_date(contact.yujifahuo_date))
    changeGrid2(tbl,6,1,contact.hetongbh)
    tbl=document.tables[1]#主机清单
    if contact.channels==None:
        changeGrid2(tbl,1,2,contact.yiqixinghao)
    else:
        changeGrid2(tbl,1,2,contact.yiqixinghao+" "+contact.channels)
    if contact.yiqixinghao[0]=='C':
        changeGrid2(tbl,2,1,"")
        pass
        #changeGrid2(tbl,2,3,"1根")
    elif contact.yiqixinghao[0]=='O':
        changeGrid2(tbl,2,3,"3根")
    elif contact.yiqixinghao[0]=='N':
        changeGrid2(tbl,2,3,"3根")
    else :
        changeGrid2(tbl,2,1,"")
    tbl=document.tables[2]#配件清单
    print(tbl.cell(0,0).text)
    items=[]
    items2=[]
    style = document.styles.add_style('me_underline', WD_STYLE_TYPE.PARAGRAPH)
    style.font.underline=True
    # for cp in contact.usepack_set.all():
    #     for pi in cp.pack.packitem_set.all():
    #         pi.item.ct=pi.ct
    #         if not pi.quehuo:
    #             items=addItem(items,pi.item)
    #         else:
    #             items2=addItem(items2,pi.item)
    (items,items2)=contact.huizong()
    for item in items:

        tmp_row=tbl.add_row()
        
        # if item.leijia:
        #     tmp_row.style.font.italic = True
        columns= tmp_row.cells
        if item.bh!=None:
            setCell(columns[0],item.bh,item.leijia)
        setCell(columns[1],item.name,item.leijia)
        if item.guige!=None:
            setCell(columns[2],item.guige,item.leijia)
        if item.danwei==None:
            item.danwei=""
        if item.leijia:
            setCell(columns[3],str(item.ct)+item.danwei,item.leijia)
        else:
            setCell(columns[3],str(item.ct)+item.danwei,item.leijia)

        if item.beizhu!=None:
            setCell(columns[5],item.beizhu,item.leijia)
        else:
            setCell(columns[5],"",item.leijia)
        setCell(columns[4],"",item.leijia)
    if len(items2)>0:
        document.add_page_break()
        p=document.add_paragraph('短缺物资清单')
        print(dir(p))
        p.alignment=1
        # # print(dir(p.paragraph_format))
        r=p.runs[0]
        # print(r.font)
        # print(r.font.size)
        # print(dir(r))
        r.font.size=203200 #
        # print(r.style.name)
        # print(r.part)
        # print(dir(r.part))


        table = document.add_table(rows=1, cols=4)
        hdr_cells = table.rows[0].cells
        borderCells(hdr_cells)
        hdr_cells[0].text = '编号'

        hdr_cells[1].text = '名称'
        hdr_cells[2].text = '规格'
        hdr_cells[3].text = '数量'
        for item in items2:
            row_cells = table.add_row().cells
            borderCells(row_cells)
            if item.bh!=None:
                row_cells[0].text = item.bh
            row_cells[1].text = item.name
            if item.guige!=None:
                row_cells[2].text = item.guige
            row_cells[3].text = str(item.ct)+item.danwei
    s=BytesIO()
    document.save(s)
    s.seek(0)
    data=s.read()
    return data
def llenar_inter_calc(nombre_archivo):
    archivo = Document(nombre_archivo)
    general = pd.read_csv("./archivos/current_general.csv",
                          sep=";",
                          encoding="latin")
    igm = str(general.iloc[0]["igm"])
    if igm == nan: igm = "IGM"
    archivo.add_page_break()
    archivo.add_heading("DESCRIPCIÓN MICROSCÓPICA - " + igm)
    archivo.add_paragraph()
    archivo.add_heading("TEXTURA - COMPOSICIÓN", 2)
    archivo.add_paragraph()
    lista = ['HOMOGENEIDAD DE LA ROCA: ', 'ALOQUÍMICOS_____(%)']
    for i in lista:
        p1 = archivo.add_paragraph()
        r1 = p1.add_run(i)
        r1.italic = True
        r1.bold = True
        p1.add_run(" ")
    p1 = archivo.add_paragraph()

    lista2 = [
        'Bioclastos_____(%)',
        'Tipo(s), rango de tamaño, selección y redondez:', 'Peloides _____(%)',
        'Tamaño y origen:', 'Ooides_____(%)',
        'Tamaño, forma, tipo y estructura interna:', 'Intraclastos _____(%)',
        'Tamaño, redondez y selección:', 'Oncoides _____(%)',
        'Tamaño, forma y estructura interna:', 'Otros Aloquímicos	_____(%)',
        'Tipo(s), tamaño(s), forma(s) y porcentajes:', 'Terrígenos		(%)',
        'Tipo(s), tamaño(s) y porcentaje(s):',
        'Minerales Autigénicos _____(%)', 'Tipo(s), tamaño(s),'
        'forma(s) y porcentajes:',
        'Extraclastos (fragmentos de rocas carbonatadas) _____(%)',
        'Tipo(s), tamaño(s), redondez y porcentajes:', 'ORTOQUÍMICOS _____(%)',
        'Tipo(s), distribución'
        'y porcentaje(s):', 'CEMENTO ESPARÍTICO: _____(%)',
        'Tamaño de cristales, forma de cristales y '
        'distribución:', 'SOPORTE DE LA ROCA:',
        'Granos- aloquímicos _____%	Lodo calcáreo o micrita	_____% ',
        'CONTACTO ENTRE GRANOS:',
        'Flotante_____% Tangencial_____% \n Longitudinal_____ %'
        'Cóncavo-convexo_____ %	Suturado_____%', 'POROSIDAD:_____%',
        'Primaria:_____%	Secundaria:_____% \n'
        'Tipo(s), origen y descripción:'
    ]
    contador = 0
    for i in lista2:
        if contador % 2 == 0:
            p1 = archivo.add_paragraph()
            r1 = p1.add_run(i)
            r1.italic = True
            r1.bold = True
            p1.add_run(" ")
        else:
            p1 = archivo.add_paragraph()
            r1 = p1.add_run(i)
            p1.add_run(" ")
        contador = contador + 1
    archivo.add_paragraph()
    archivo.add_heading('CLASIFICACIÓN DE LA ROCA – ' + igm + ":")
    archivo.add_paragraph()
    lista3 = [
        'Folk (1962):', 'Dunham (1962):', 'Gama textural de Folk (1962):'
    ]
    for i in lista3:
        p1 = archivo.add_paragraph()
        r1 = p1.add_run(i)
        r1.italic = True
        r1.bold = True
        p1.add_run(" ")
    archivo.add_paragraph()
    archivo.add_heading('DIAGÉNESIS:')
    lista4 = ['Autigénesis:', 'Recristalización: ']
    for i in lista4:
        p1 = archivo.add_paragraph()
        r1 = p1.add_run(i)
        r1.italic = True
        r1.bold = True
        p1.add_run(" ")
    archivo.save(nombre_archivo)
예제 #29
0
            def escribirDocumentoAmbos(red, *data):

                diccionario = [x for x in data]
                
                if len(diccionario) is 1:
                    if len(diccionario[0]) is 11:
                        facedic = diccionario[0]
                        
                    elif len(diccionario[0]) is 10:
                        instadic = diccionario[0]
                        
                elif len(diccionario) is 2:
                    if len(diccionario[0]) > len(diccionario[1]):
                        facedic = diccionario[0]
                        instadic = diccionario[1]   
                    else:
                        instadic = diccionario[0]
                        facedic = diccionario[1]

                #Nombres de los archivos guardados
                desktop = os.getcwd()
                fscreenshot = os.path.join(desktop, 'screenshotfacebookpost.png')
                iscreenshot = os.path.join(desktop, 'screenshotinstagrampost.png')

                document = Document()
                p = document.add_paragraph()
                p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
                p.add_run('Informe {0} {1} {2}'.format(pagename, mes, anho)).bold = True

                if (red == 'facebook') or (red == 'ambos'):
                    #Descarga de Facebook Diccionario
                    ftotaldeposts = facedic['totaldeposts']
                    fseguidorestotal = facedic['seguidorestotal']
                    fimpresionespromedio = facedic['impresionespromedio']
                    freachpromedio = facedic['reachpromedio'] 
                    fsavedpromedio = facedic['savedpromedio']
                    fimpresionespop = facedic['impresionespop']
                    fengagementpop = facedic['engagementpop']
                    freachpop = facedic['reachpop']
                    fsavedpop = facedic['savedpop']
                    flinkpost = facedic['linkpost']
                    fnuevolikes = facedic['nuevolikes']
                    #Cuenta de Facebook
                    p2 = document.add_paragraph()
                    p2.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
                    p2.add_run('Facebook').bold = True

                    p3 = document.add_paragraph()
                    p3.add_run('{0} nuevos likes (llegando a {1}).'.format(fnuevolikes, fseguidorestotal))

                    p4 = document.add_paragraph()
                    p4.add_run('{0} posts emitidos.'.format(ftotaldeposts))

                    p5 = document.add_paragraph()
                    p5.add_run('{0} usuarios en promedio que realizaron algún tipo de interacción.'.format(fsavedpromedio))

                    p6 = document.add_paragraph()
                    p6.add_run('{0} personas alcanzadas (promedio de usuarios únicos en cada post).'.format(freachpromedio))

                    p7 = document.add_paragraph()
                    p7.add_run('{0} impresiones en promedio.'.format(fimpresionespromedio))

                    #TODO tasa de participación como criterio
                    #p75 = document.add_paragraph()
                    #p75.add_run('{0}% tasa de participación (engagement rate) promediada.'.format(mediaER))

                    p8 = document.add_paragraph('Post destacado:')

                    #Acceso a internet y extración de imagen del post más popular.
                    try:
                        paramsf = urlencode({'url':'{0}'.format(flinkpost), 
                            'access_key':'3dfe7afa8bafb96cdb0215bb12974a89'})
                        urlretrieve('https://api.screenshotlayer.com/api/capture?' 
                            + paramsf, fscreenshot)
                        pimage = document.add_picture(fscreenshot, width=Inches(5))
                    except:
                        p00 = document.add_paragraph()
                        p00.add_run('{0}'.format(flinkpost))

                    #p85 = document.add_paragraph()
                    #p85.add_run('{0}% tasa de participación.'.format(masER))

                    p9 = document.add_paragraph()
                    p9.add_run('{0} usuarios únicos alcanzados.'.format(freachpop))

                    p10 = document.add_paragraph()
                    p10.add_run('{0} impresiones.'.format(fimpresionespop))

                    p11 = document.add_paragraph()
                    p11.add_run('{0} usuarios que interactuaron.'.format(fengagementpop))

                    document.add_page_break()

                if (red == 'instagram') or (red == 'ambos'):
                    #Descarga de Instagram Diccionario
                    itotaldeposts = instadic['totaldeposts']
                    iseguidorestotal = instadic['seguidorestotal']
                    iimpresionespromedio = instadic['impresionespromedio']
                    ireachpromedio = instadic['reachpromedio'] 
                    isavedpromedio = instadic['savedpromedio']
                    iimpresionespop = instadic['impresionespop']
                    iengagementpop = instadic['engagementpop']
                    ireachpop = instadic['reachpop']
                    isavedpop = instadic['savedpop']
                    ilinkpost = instadic['linkpost']

                    pgram = document.add_paragraph()
                    pgram.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
                    pgram.add_run('Instagram').bold = True

                    pgram0 = document.add_paragraph()
                    pgram0.add_run('{0} nuevos seguidores.'.format(iseguidorestotal))

                    pgram1 = document.add_paragraph()
                    pgram1.add_run('{0} posts realizados.'.format(itotaldeposts))

                    pgram2 = document.add_paragraph()
                    pgram2.add_run('{0} impresiones (en promedio).'.format(iimpresionespromedio))

                    pgram3 = document.add_paragraph()
                    pgram3.add_run('{0} usuarios alcanzados (en promedio).'.format(ireachpromedio))

                    pgram4 = document.add_paragraph()
                    pgram4.add_run('{0} posts guardados.'.format(isavedpromedio))

                    pgram5 = document.add_paragraph('Post destacado:')

                    #Acceso a internet y extración de imagen del post más popular.
                    try:
                        paramsi = urlencode({'url':'{0}'.format(ilinkpost), 
                            'access_key':'3dfe7afa8bafb96cdb0215bb12974a89'})
                        urlretrieve('https://api.screenshotlayer.com/api/capture?' 
                            + paramsi, iscreenshot)
                        pimage2 = document.add_picture(iscreenshot, width=Inches(5))
                    except:
                        pgram00 = document.add_paragraph()
                        pgram00.add_run('{0}'.format(ilinkpost))

                    pgram6 = document.add_paragraph()
                    pgram6.add_run('{0} interacciones de usuarios (likes + comentarios).'.format(iengagementpop))

                    pgram7 = document.add_paragraph()
                    pgram7.add_run('{0} impresiones.'.format(iimpresionespop))

                    pgram8 = document.add_paragraph()
                    pgram8.add_run('{0} usuarios alcanzados.'.format(ireachpop))

                    document.add_page_break()

                #Guardado del documento
                document.save('{0}'.format(futuro))

                #Eliminación de imágenes
                if os.path.isfile(fscreenshot):
                    os.remove(fscreenshot)

                if os.path.isfile(iscreenshot):
                    os.remove(iscreenshot)

                #Apertura de archivo
                if sys.platform == 'linux':
                    os.system("xdg-open " + futuro)
                elif sys.platform == 'win32':
                    os.startfile(futuro)
                else:
                    opener = "open" if sys.platform == 'darwin' else 'xdg-open'
                    subprocess.call([opener, futuro])
예제 #30
0
class Renderer(abstractRenderer.AbstractRenderer, config):
    def __init__(self, inputDir, outputDir, outputName):
        abstractRenderer.AbstractRenderer.__init__(self, inputDir, outputDir,
                                                   outputName, config)
        self.document = Document()
        self.currentParagraph = self.document.add_paragraph()
        self.outputFilename = os.path.join(outputDir, outputName + '.docx')
        self.inputDir = inputDir
        self.f = codecs.open('/dev/null', 'w', 'utf_8_sig')
        self.currentChapter = ''
        self.currentBook = ''
        self.in_nd = False
        self.in_footnote = False
        # Old:
        # Flags
        self.printerState = {u'li': False, u'd': False, u'm': False}
        self.smallCapSections = True  # Sometimes we don't want to do this, like for Psalms
        self.justDidLORD = False
        self.justDidNB = False
        self.doNB = False
        self.narrower = False
        self.doChapterOrVerse = u''
        self.smallcaps = False

    def render(self, order='normal'):
        self.loadUSFM(self.inputDir)
        self.run(order)
        self.document.save(self.outputFilename)

    #
    #   Support
    #

    def startNarrower(self, n):
        s = u'}' if self.narrower else u'\n\\blank[medium] '
        self.narrower = True
        s = s + u'\n\\noindentation \\Q{' + str(n) + u'}{'
        self.doNB = True
        return s

    def stopNarrower(self):
        s = u'}\n\\blank[medium] ' if self.narrower else u''
        self.narrower = False
        return s

    def escapeText(self, s):
        return s.replace('&', '\\&').replace('%', '\\%')

    def startLI(self):
        if self.printerState[u'li'] == False:
            self.printerState[u'li'] = True
            #return u'\startitemize \item '
            return ur'\startexdent '
        else:
            #return u'\item '
            return ur'\par '

    def stopLI(self):
        if self.printerState[u'li'] == False:
            return u''
        else:
            self.printerState[u'li'] = False
            #return u'\stopitemize'
            return ur'\stopexdent '

    def startD(self):
        if self.printerState[u'd'] == False:
            self.printerState[u'd'] = True
        return u'\par {\startalignment[middle] \em '

    def stopD(self):
        if self.printerState[u'd'] == False:
            return u''
        else:
            self.printerState[u'd'] = False
            return u'\stopalignment }'

    def startM(self):
        r = self.stopD() + self.stopLI() + self.stopNarrower()
        self.printerState[u'm'] = True
        return r + ur'\par {\startalignment[flushleft] '

    def stopM(self):
        if self.printerState[u'm'] == False:
            return u''
        else:
            self.printerState[u'm'] = False
            return u'\stopalignment }'

    def newLine(self):
        s = u'\n\par \n'
        if self.doNB:
            self.doNB = False
            self.justDidNB = True
            s = s + ur'\noindentation '
        elif self.justDidNB:
            self.justDidNB = False
            s = s + ur'\indentation '
        return s

    #
    #   Used helpers for Docx
    #
    def clean(self, token):
        return token.getValue().replace('~', ' ')

    def newPara(self):
        self.currentParagraph = self.document.add_paragraph()

    #
    #   Tokens
    #

    def render_h(self, token):
        self.document.add_page_break()
        self.currentBook = token.getValue()

    def render_mt1(self, token):
        self.document.add_heading(self.clean(token), level=0)

    def render_mt2(self, token):
        self.document.add_heading(self.clean(token), level=1)

    def render_ms1(self, token):
        self.document.add_heading(self.clean(token), level=2)

    def render_ms2(self, token):
        self.document.add_heading(self.clean(token), level=3)

    def render_p(self, token):
        self.newPara()

    def render_pi(self, token):
        self.newPara()
        self.currentParagraph.left_indent = Inches(1)

    def render_s1(self, token):
        self.document.add_heading(self.clean(token), level=4)

    def render_s2(self, token):
        self.document.add_heading(self.clean(token), level=5)

    def render_c(self, token):
        self.currentChapter = token.getValue()

    def render_v(self, token):
        if token.getValue() == '1':
            run = self.currentParagraph.add_run(self.currentBook + ' ' +
                                                self.currentChapter + ' ')
            run.font.color.rgb = RGBColor(255, 0, 0)
        else:
            run = self.currentParagraph.add_run(token.getValue() + ' ')
            run.font.color.rgb = RGBColor(0, 140, 0)
        run.font.superscript = True

    def render_text(self, token):
        run = self.currentParagraph.add_run(self.clean(token) + ' ')
        if self.in_nd:
            run.font.small_caps = True
        elif self.in_footnote:
            run.font.color.rgb = RGBColor(0, 0, 140)
        else:
            pass

    def render_q1(self, token):
        self.newPara()
        self.currentParagraph.paragraph_format.space_after = Pt(0)

    def render_q2(self, token):
        self.newPara()
        self.currentParagraph.paragraph_format.space_after = Pt(0)
        self.currentParagraph.add_run('\t')

    def render_q3(self, token):
        self.newPara()
        self.currentParagraph.paragraph_format.space_after = Pt(0)
        self.currentParagraph.add_run('\t\t')

    def render_nb(self, token):
        self.newPara()
        self.currentParagraph.left_indent = Inches(0)

    def render_b(self, token):
        self.newPara()
        self.currentParagraph.paragraph_format.space_after = Pt(0)

    def render_d(self, token):
        self.newPara()
        self.currentParagraph.paragraph_format.space_after = Pt(0)

    def render_f_s(self, token):
        run = self.currentParagraph.add_run(' [[ ')
        run.font.color.rgb = RGBColor(0, 0, 140)
        self.in_footnote = True

    def render_f_e(self, token):
        run = self.currentParagraph.add_run(' ]] ')
        run.font.color.rgb = RGBColor(0, 0, 140)
        self.in_footnote = False

    def render_nd_s(self, token):
        pass

    def render_nd_e(self, token):
        run = self.currentParagraph.runs[-1]
        run.font.small_caps = True

    def render_em_s(self, token):
        pass

    def render_em_e(self, token):
        run = self.currentParagraph.runs[-1]
        run.italic = True

    # SELAH
    def render_qs_s(self, token):
        pass

    def render_qs_e(self, token):
        run = self.currentParagraph.runs[-1]
        run.italic = True

    def render_wj_s(self, token):
        pass

    def render_wj_e(self, token):
        run = self.currentParagraph.runs[-1]
        run.font.color.rgb = RGBColor(140, 0, 0)

    def render_is1(self, token):
        self.render_s1(token)

    def render_ip(self, token):
        self.render_p(token)

    def render_iot(self, token):
        self.render_q1(token)

    def render_io1(self, token):
        self.render_q2(token)

    def render_pb(self, token):
        self.document.add_page_break()

    def render_m(self, token):
        self.render_p(token)

    #
    #   Introductory codes
    #

    introTeXt = unicode(r""" """)
    closeTeXt = ur""" """
예제 #31
0
##### set data originally to hold nothining
data = None

# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
print("Writing files....")

### merged doc paths
invoice_doc_path_pp = sub_path_pp+'/pp_invoice_'+INVOICE_MONTH+'_'+INVOICE_YEAR+'.docx'
invoice_doc_path_gg = sub_path_gg+'/gg_invoice_'+INVOICE_MONTH+'_'+INVOICE_YEAR+'.docx'

### merged pp doc
# first page plus page break
doc_pp = Document(fpage)
doc_pp.add_page_break()
# compose it for appends
composer_doc_pp = Composer(doc_pp)

### merged gg doc
# first page plus page break
doc_gg = Document(fpage)
doc_gg.add_page_break()
# compose it for appends
composer_doc_gg = Composer(doc_gg)

# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# CONCATENATE DOC through loop

# loop via iterator
예제 #32
0
def docx_save(imie, nazwisko, numer_warantu, tablica1, tablica2):
    #zadanie 1
    document = Document()
    document.add_heading(
        '%d %s %s' % (datetime.datetime.now().year, imie, nazwisko), 0)
    document.add_heading('WYCIEP projekt 2', 0)
    document.add_page_break()
    document.add_heading('ZADANIE 1 ', 1)
    document.add_paragraph(
        'Przez rurociąg wykonany ze stali węglowej (0,15% C) o średnicy wewnętrznej dw [m] i zewnętrznej dz=dw+0,008 [m] oraz długości L [m] przepływa woda [ton/dobę] o temperaturze wlotowej Tw [K]. Rurociąg jest umieszczony w hali produkcyjnej, w której panuje stała temperatura powietrza równa Tp [K]. Określić straty cieplne i temperaturę wylotową cieczy w zależności od natężenia masowego przepływu w zakresie liczby Reynoldsa Re=100-105. Rozwiązanie podać w formie wykresu. '
    )
    document.add_heading('Dane: ', 1)
    document.add_paragraph(
        'Tw=%s[k]' %
        (csv_load("wyciep projekt 2 warianty.csv", numer_warantu, 2)))
    document.add_paragraph(
        'Tp=%s[k]' %
        (csv_load("wyciep projekt 2 warianty.csv", numer_warantu, 3)))
    document.add_paragraph(
        'L=%s[m]' %
        (csv_load("wyciep projekt 2 warianty.csv", numer_warantu, 4)))
    document.add_paragraph(
        'dw=%s[m]' %
        (csv_load("wyciep projekt 2 warianty.csv", numer_warantu, 5)))
    document.add_paragraph(
        'dz=%s[m]' %
        (float(csv_load("wyciep projekt 2 warianty.csv", numer_warantu, 5)) +
         0.008))
    document.add_heading('Analiza problemu', 1)
    document.add_paragraph(
        'Problem przedstawiony w zadaniu polega na wyznaczeniu temperatury wylotowej, którą mamy uzależnić od natężenia masowego przepływu w zakresie liczby Reynoldsa Re=100- 105. W zadaniu mamy powiedziane, że przez rurociąg przepływa woda, więc mamy do czynienia z mechanizmem konwekcyjnym. Wewnątrz rurociągu występuje konwekcja wymuszona, ponieważ występuje ruch płynu, natomiast w jego otoczeniu- swobodna, gdyż powietrze tylko otacza rurociąg i jest to ruch samoistny.'
    )
    document.add_paragraph(
        'Ciepło jakie niesie ze sobą ciecz przenika przez ścianki (zakładam ze rurociąg jest ze stali 0.15% C- [2] Gogół tablica 4.1 str.53) – na początku zachodzi wnikanie od płynu do ścianki, później przewodzenie wewnątrz ścianki a na końcu wnikanie ze ścianki do powietrza.'
    )
    document.add_paragraph(
        'W zależności od konwekcji liczba Nusselta jest funkcją liczb: Reynoldsa i Prandtla dla wymuszonej, Prandtla i Grashofa dla swobodnej. Liczbą Nusselta nazywamy stosunek szybkości wnikania ciepła do szybkości przewodzenia ciepła. Liczba Reynoldsa to siły bezwładności przez siły tarcia. Liczba Prandtla to siła molekularnego przenoszenia pędu przez szybkość przewodzenia ciepła. Liczba Grashofa to siła wyporu powstała na skutek różnicy temperatur przez siły tarcia. Są to liczby kryterialne.'
    )
    document.add_page_break()
    document.add_heading('Koncepcja rozwiązania', 1)
    document.add_paragraph(
        'Własności fizykochemiczne cieczy są zależne od temperatury',
        style='ListBullet')
    document.add_paragraph('Wewnątrz rurociągu występuje konwekcja wymuszona',
                           style='ListBullet')
    document.add_paragraph('Pole temperatur jest ustalone', style='ListBullet')
    document.add_paragraph(
        'Temperatura ścianki wielkością stalą na całej długości rurociągu',
        style='ListBullet')
    document.add_heading(
        'Zakładam temperaturę wylotową, a następnie obliczam temperaturę średnią :',
        3)
    table = document.add_table(rows=1, cols=3)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = ''
    hdr_cells[1].text = 'Tsr=(Tw-Twylot)/2'
    hdr_cells[2].text = ''
    document.add_paragraph('Tw – temperatura wlotowa wody')
    document.add_paragraph('Twylot – założona temperatura wylotowa wody')
    document.add_paragraph('')
    document.add_paragraph(
        'Następnie korzystając z tabel zawartych w książce Wiesława Gogóła „Wymiana ciepła – tablice i wykresy” interpoluję potrzebne wielkości fizykochemiczne w Excelu.'
    )
    document.add_paragraph('ρ  – gęstość wody[kg/m3]')
    document.add_paragraph('μ – lepkość dynamiczna wody[Pa*s]')
    document.add_paragraph('Cp– ciepło właściwe wody [J/(kg*K)]')
    document.add_paragraph('λ– współczynnik przewodzenia ciepła wody')
    document.add_heading('Obliczam prędkość przepływu wody:', 3)
    table = document.add_table(rows=1, cols=3)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = ''
    hdr_cells[1].text = 'Re=(u*dw*ρ)/μ => u=(Re*μ)/(dw*ρ)'
    hdr_cells[2].text = ''
    document.add_paragraph('Re- Liczba Reynoldsa w zakresie 100<Re<105')
    document.add_paragraph('μ– lepkość dynamiczna wody [Pa*s] ')
    document.add_paragraph('ρ – gęstość wody [kg/m3]')
    document.add_paragraph('dw– średnica wewnętrzna rury [m]')
    document.add_page_break()
    document.add_heading('Obliczam natężenie masowe przepływu:', 3)
    table = document.add_table(rows=1, cols=3)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = ''
    hdr_cells[1].text = 'm[kg/s]=(u*ρ*π*dw^2)/4'
    hdr_cells[2].text = ''
    document.add_heading('Z bilansu entalpowego obliczam natężenie przepływu:',
                         3)
    table = document.add_table(rows=1, cols=3)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = ''
    hdr_cells[1].text = 'Q=m*Cp*(Tw-Twylot)'
    hdr_cells[2].text = ''
    document.add_paragraph('m [kg/s] – natężenie masowe przepływu')
    document.add_paragraph('Cp [J/(kg*K)] – ciepło właściwe wody')
    document.add_paragraph('Tw [K] – temperatura wlotowa wody')
    document.add_paragraph('Twylot  [K] – założona temperatura wylotowa wody')
    document.add_paragraph(
        'Następnie interpoluję liczbę Prandtla oraz zakładam temperaturę ścianki rurociągu.'
    )
    document.add_heading(
        'Następnie korzystając z odpowiedniej korelacji dla określonego przepływu obliczam liczbę Nusselta:',
        3)
    document.add_paragraph(
        'a) przepływ laminarny (Re<2000). Długość rury wywiera duży wpływ – ze wzrostem długości rury średnia wartość α zmienia się (Hobler str.195):'
    )
    document.add_paragraph(
        '                 Nu = 1.86*((Pr*Re*dw/L)^(1/3))*((μ/μs)^0.14)')
    document.add_paragraph(
        'b) przepływ przejściowy (2000<Re<10000) Gogół tablica 6.1 str.102:')
    document.add_paragraph(
        '                 Nu = K0 * Pr^0,43 * (Pr*λsc / Cpsc*μsc)^0,25')
    document.add_paragraph('')
    table = document.add_table(rows=2, cols=13)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = 'Re*e-3'
    hdr_cells[1].text = '2,2'
    hdr_cells[2].text = '2,3'
    hdr_cells[3].text = '2,5'
    hdr_cells[4].text = '3,0'
    hdr_cells[5].text = '3,5'
    hdr_cells[6].text = '4'
    hdr_cells[7].text = '5'
    hdr_cells[8].text = '6'
    hdr_cells[9].text = '7'
    hdr_cells[10].text = '8'
    hdr_cells[11].text = '9'
    hdr_cells[12].text = '10'
    hdr_cells = table.rows[1].cells
    hdr_cells[0].text = 'K0'
    hdr_cells[1].text = '2,2'
    hdr_cells[2].text = '3,6'
    hdr_cells[3].text = '4,9'
    hdr_cells[4].text = '7,5'
    hdr_cells[5].text = '10'
    hdr_cells[6].text = '12,2'
    hdr_cells[7].text = '16,5'
    hdr_cells[8].text = '20'
    hdr_cells[9].text = '24'
    hdr_cells[10].text = '27'
    hdr_cells[11].text = '30'
    hdr_cells[12].text = '33'
    document.add_paragraph('')
    document.add_paragraph('c) przepływ burzliwy (Re>10000 i 0,7<Pr<16700):')
    document.add_paragraph(
        '                 Nu = 0,023 * Re^0,8 * Pr^0,33 * (μ/μsc)^0,14')
    document.add_heading(
        'Następnie  znając  liczbę  Nusselta obliczam współczynnik wnikania ciepła αw. ',
        3)
    document.add_paragraph(
        '                 Nu = (αw*dw)/λ  =>   αw=(Nu*λ)/dw')
    document.add_paragraph('Nu – liczba Nusselta dla przepływu')
    document.add_paragraph(
        'λ [W/(m*K)] – współczynnik przewodzenia ciepła wody')
    document.add_paragraph('dw [m] – średnica wewnętrzna rury')
    document.add_paragraph('')
    document.add_paragraph('')
    document.add_heading(
        'Obliczam właściwą temperaturę ścianki z bilansu cieplnego:', 3)
    document.add_paragraph(
        '          Q = αw * π * dw * L * (Tsr - Tścianki) => Tścianki = Tsr - Q/(αw * π * dw * L)'
    )
    document.add_paragraph('Q [W] – strumień ciepła')
    document.add_paragraph('dw [m] – średnica wewnętrzna rury')
    document.add_paragraph('L  [m] – długość rury')
    document.add_paragraph('Tśr [K] – średnia temperatura wody w rurze')
    document.add_paragraph(
        'Jeżeli wartość założona nie zgadza się z obliczoną podstawiam znowu temperaturę i obliczam do momentu aż założona i wyliczona będą się zgadzały '
    )
    document.add_paragraph(
        'Obliczam temperaturę zewnętrzną rury z bilansu cieplnego:')
    document.add_paragraph(
        '        Q/L=k*ΔT=ln(dz/dw)*(Tścianki - Tść.zew)/(2*π*λstali)')
    document.add_paragraph(
        '        Tść.zew=Tścianki - Q/L * (ln(dz/dw)/(2*π*λstali))')
    document.add_paragraph(
        'λstali  [W/(m*K)] – współczynnik przewodzenia stali (0,15% C)')
    document.add_paragraph('dz [m] – średnica zewnętrzna rury')
    document.add_paragraph('dw [m] – średnica wewnętrzna rury')
    document.add_paragraph('Tścianki [K] – temperatura wewnętrzna ścianki')
    document.add_paragraph('Q [W] – strumień ciepła')
    document.add_paragraph('L– długość rury')
    document.add_heading(
        'Obliczam temperaturę warstwy przyściennej jako średnią powietrza i odczytuję dane fizykochemiczne:',
        3)
    document.add_paragraph('        Tpśr = (Tść.zew + T)/2')
    document.add_paragraph('ρ [kg/m3] – gęstość powietrza')
    document.add_paragraph('μ [Pa*s] – lepkość dynamiczna powietrza')
    document.add_paragraph('Cp [J/(kg*K)] – ciepło właściwe powietrza')
    document.add_paragraph(
        'λ [W/(m*K)] – współczynnik przewodzenia ciepła powietrza')
    document.add_paragraph('Pr [-] - liczba Prandtla')
    document.add_heading('Obliczam liczbę Grashofa:', 3)
    document.add_paragraph(
        '        Gr = (g * dz^3 / v^2) * β * ΔT = (g * dz^3 / (μ/ρ)^2) * (Tść.zew -Tp)/Tp'
    )
    document.add_paragraph('β - współczynnik rozszerzalności termicznej')
    document.add_paragraph('g [m/s] – przyspieszenie ziemskie')
    document.add_paragraph('dz  [m] – średnica zewnętrzna rury')
    document.add_paragraph('ρ  [kg/m3] – gęstość powietrza')
    document.add_paragraph('μ [Pa*s] – lepkość dynamiczna powietrza')
    document.add_paragraph(
        'Tść.zew. [K] – temperatura zewnętrznej ścianki rury ')
    document.add_paragraph('Tp [K]  - temperatura powietrza')
    document.add_heading(
        'Korzystając z odpowiedniej korelacji dla określonego przepływu obliczam liczbę Nusselta dla konwekcji swobodnej (wzór Michiejewa):',
        3)
    document.add_paragraph('        Nu = C * (Gr * Pr)^n')
    document.add_paragraph('Stałe C i n zależą od:')
    table = document.add_table(rows=4, cols=3)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = 'Gr * Pr'
    hdr_cells[1].text = 'C'
    hdr_cells[2].text = 'n'
    hdr_cells = table.rows[1].cells
    hdr_cells[0].text = '10^-3 do 5*10^2'
    hdr_cells[1].text = '1,18'
    hdr_cells[2].text = '1/8'
    hdr_cells = table.rows[2].cells
    hdr_cells[0].text = '5*10^2 do 2*10^7'
    hdr_cells[1].text = '0,54'
    hdr_cells[2].text = '1/4'
    hdr_cells = table.rows[3].cells
    hdr_cells[0].text = '2*10^7 do 10^13'
    hdr_cells[1].text = '0,135'
    hdr_cells[2].text = '1/3'
    document.add_heading(
        'Znając liczbę Nusselta dla powietrza obliczam współczynnik wnikania ciepła od zewnętrznej ścianki rury do powietrza αp.',
        3)
    document.add_paragraph(
        '        Nu = (αp *dz)/λpow   =>  αp = (Nu * λpow)/dz')
    document.add_heading('Obliczam współczynnik oporu R', 3)
    document.add_paragraph(
        '      R = 1/(αw * dw * π) + 1/(2*π*λstali)*ln(dz/dw) + 1/(αp * dz * π)'
    )
    document.add_paragraph(
        'αw [W/(m2*K)] – współczynnik wnikania ciepła po stronie wody')
    document.add_paragraph(
        'αp  [W/(m2*K)] - współczynnik wnikania ciepła od zewnętrznej ścianki rury do powietrza '
    )
    document.add_paragraph(
        'λstali [W/(m*K)] – współczynnik przewodzenia stali ( 0,15% C)')
    document.add_paragraph('dz [m] – średnica zewnętrzna rury')
    document.add_paragraph('dw [m] – średnica wewnętrzna rury')
    document.add_paragraph('')

    #wukresy do worda
    print(numer_warantu, "numer wariantu")
    document.add_picture('wykresy/%s.1.png' % numer_warantu)
    document.save('wordy zrobione/%s_%s.docx' % (imie, nazwisko))
예제 #33
0
  'Medium List 1',
  'Medium List 2',
  'Medium Shading 1',
  'Medium Shading 2',
]

# Create an example of all the tables
for table_type in table_types:
    for idx in range(1, 6):
        style = '%s - %s' % (table_type, 'Accent %d' % (idx))
        document.add_heading(style, level=2)
        try:
            table = document.add_table(rows=1, cols=3, style=style.replace(' ', ''))
            hdr_cells = table.rows[0].cells
            hdr_cells[0].text = 'Qty'
            hdr_cells[1].text = 'Id'
            hdr_cells[2].text = 'Desc'
            for item in recordset:
                row_cells = table.add_row().cells
                row_cells[0].text = str(item[0])
                row_cells[1].text = str(item[1])
                row_cells[2].text = str(item[2])
        except:
            error = 'Failed to process: %s' % (style)
            document.add_paragraph(error)
            print(error)

document.add_page_break()

document.save(doc_name)
예제 #34
0
class DocxCaseInfo:
    def __init__(self, path):
        self.path = path
        self.document = Document()
        self.document.styles['Normal'].font.name = u'宋体'
        self.document.styles['Normal']._element.rPr.rFonts.set(
            qn('w:eastAsia'), u'宋体')
        self.table = ''
        self.firstflag = True

    # 添加表格
    def add_table(self, tablename):
        if self.firstflag is True:
            self.firstflag = False
        else:
            self.document.add_page_break()
        self.create_head(tablename)
        # 创建表格
        self.table = self.document.add_table(rows=12,
                                             cols=4,
                                             style='Table Grid')
        self.init_table()

    def add_table_1(self, tablename):
        if self.firstflag is True:
            self.firstflag = False
        else:
            self.document.add_page_break()
        self.create_head(tablename)
        # 创建表格
        self.table = self.document.add_table(rows=2,
                                             cols=5,
                                             style='Table Grid')
        self.init_table_1()

    def add_table_2(self, tablename, rows):
        if self.firstflag is True:
            self.firstflag = False
        else:
            self.document.add_page_break()
        self.create_head(tablename)
        # 创建表格
        self.table = self.document.add_table(rows=rows,
                                             cols=6,
                                             style='Table Grid')
        self.init_table_2()

    def add_table_3(self, tablename):
        if self.firstflag is True:
            self.firstflag = False
        else:
            self.document.add_page_break()
        self.create_head(tablename)

    # 初始化表上文字
    def create_head(self, tablename):

        p = self.document.add_paragraph('', style='Heading1')
        r = p.add_run(tablename)
        r.font.name = "宋体"

        r._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
        # 上下间距
        p.paragraph_format.space_before = Pt(18)
        p.paragraph_format.space_after = Pt(12)
        # 首行缩进
        p.paragraph_format.first_line_indent = Inches(0.3)
        r.font.color.rgb = RGBColor(0, 0, 0)

    # 初始化表格
    def init_table(self):
        for rowcnt in range(len(self.table.rows)):
            row = self.table.rows[rowcnt]
            row.cells[0].vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER

            self._row_deal(row, rowcnt)

            if rowcnt == 0:
                row.height = Cm(0.7)
                r = row.cells[0].paragraphs[0].add_run('需求编号')
                r.bold = True
                r = row.cells[2].paragraphs[0].add_run('编制人')
                r.bold = True
            elif rowcnt == 1:
                row.height = Cm(0.7)
                r = row.cells[0].paragraphs[0].add_run('版本')
                r.bold = True
                r = row.cells[2].paragraphs[0].add_run('审定人')
                r.bold = True
            elif rowcnt == 2:
                row.height = Cm(0.7)
                r = row.cells[0].paragraphs[0].add_run('测试用例编号')
                r.bold = True
                r = row.cells[2].paragraphs[0].add_run('测试名称')
                r.bold = True
            elif rowcnt == 3:
                row.height = Cm(1.5)
                r = row.cells[0].paragraphs[0].add_run('测试目的')
                r.bold = True
            elif rowcnt == 4:
                row.height = Cm(2)
                r = row.cells[0].paragraphs[0].add_run('测试条件说明')
                r.bold = True
            elif rowcnt == 5:
                row.height = Cm(2)
                r = row.cells[0].paragraphs[0].add_run('测试步骤')
                r.bold = True
            elif rowcnt == 6:
                row.height = Cm(2)
                r = row.cells[0].paragraphs[0].add_run('期待输出结果')
                r.bold = True
            elif rowcnt == 7:
                row.height = Cm(2)
                r = row.cells[0].paragraphs[0].add_run('实际输出结果')
                r.bold = True
            elif rowcnt == 8:
                row.height = Cm(2)
                r = row.cells[0].paragraphs[0].add_run('测试报告结论')
                r.bold = True
            elif rowcnt == 9:
                row.height = Cm(0.7)
                r = row.cells[0].paragraphs[0].add_run('测试人员')
                r.bold = True
                r = row.cells[2].paragraphs[0].add_run('测试日期')
                r.bold = True
            elif rowcnt == 10:
                row.height = Cm(0.7)
                r = row.cells[0].paragraphs[0].add_run('审查人员')
                r.bold = True
                r = row.cells[2].paragraphs[0].add_run('审查时间')
                r.bold = True
            elif rowcnt == 11:
                row.height = Cm(2)
                r = row.cells[0].paragraphs[0].add_run('审查结果')
                r.bold = True

    def _row_deal(self, row, rowcnt):
        if 2 < rowcnt <= 8 or rowcnt > 10:
            # 3行后需要合并
            row.cells[1].merge(row.cells[3])
        else:
            row.cells[2].vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER

    def init_table_1(self):
        # print(len(self.table.rows))
        for rowcnt in range(len(self.table.rows)):
            # print(rowcnt)
            row = self.table.rows[rowcnt]

            if rowcnt == 0:
                row.height = Cm(0.7)
                r = row.cells[0].paragraphs[0].add_run('测试用例总数')
                r.bold = True
                r = row.cells[1].paragraphs[0].add_run('测试通过用例数')
                r.bold = True
                r = row.cells[2].paragraphs[0].add_run('测试不通过用例数')
                r.bold = True
                r = row.cells[3].paragraphs[0].add_run('测试时间')
                r.bold = True
                r = row.cells[4].paragraphs[0].add_run('测试人员')
                r.bold = True

    def init_table_2(self):
        # print(len(self.table.rows))
        for rowcnt in range(len(self.table.rows)):
            # print(rowcnt)
            row = self.table.rows[rowcnt]

            if rowcnt == 0:
                row.height = Cm(0.7)
                r = row.cells[0].paragraphs[0].add_run('序号')
                r.bold = True
                r = row.cells[1].paragraphs[0].add_run('测试编号')
                r.bold = True
                r = row.cells[2].paragraphs[0].add_run('测试名称')
                r.bold = True
                r = row.cells[3].paragraphs[0].add_run('是否通过')
                r.bold = True
                r = row.cells[4].paragraphs[0].add_run('测试时间')
                r.bold = True
                r = row.cells[5].paragraphs[0].add_run('测试人员')
                r.bold = True

    """
    针对具体单个表格添加具体的值
    row 行号-1
    cell 列号-1
    value 填充的值
    bold 是否加粗,默认False为不加粗
    """

    def write_table(self, row, cell, value, bold=False):
        r = self.table.rows[row].cells[cell].paragraphs[0].add_run(value)
        r.bold = bold

    def save(self):

        self.document.save(self.path)
        return self.path
예제 #35
0
class ToWord:
    document = None

    def __init__(self,
                 Host=None,
                 User=None,
                 Password=None,
                 Database=None,
                 Charset=None):
        self.turnOjb = DbInfo(host=Host,
                              user=User,
                              password=Password,
                              database=Database,
                              charset=Charset)
        self.createDoc()

    def createDoc(self):
        self.document = Document()
        self.document.add_heading('数据库文档', 0)
        self.p = self.document.add_paragraph('Yearning')
        self.p.add_run('Yearning').bold = True
        self.p = self.document.add_paragraph('导出日期: %s' % datetime.now())
        self.document.add_picture('libs/logo.png', width=Inches(8))

    def exportTables(self, Conn=None, Schemal=None, TableList=None):
        '''导出指定的一些表,TableList 为表名称列表 '''

        for tableName in TableList:
            tabSet = self.turnOjb.getTableName(ConnName=Conn,
                                               SchemalName=Schemal,
                                               TableName=tableName)
            self.document.add_page_break()
            self.document.add_heading('%s' % [TB[0] for TB in tabSet][0],
                                      level=2)
            table = self.document.add_table(rows=1, cols=5)
            table.style = 'LightShading-Accent1'
            table.rows[0].cells[0].text = '字段名'
            table.rows[0].cells[1].text = '类型'
            table.rows[0].cells[2].text = '备注'
            columnSet = self.turnOjb.getTableInfo(ConnName=Conn,
                                                  SchemalName=Schemal,
                                                  TableName='%s' %
                                                  [TB[0] for TB in tabSet][0])
            for index, column in enumerate(columnSet):
                cells = table.add_row().cells
                cells[0].text = '%s' % column[4]
                cells[1].text = '%s' % column[5]
                cells[2].text = '%s' % column[6]
        time = datetime.now()
        self.document.save('./exportData/%s_%s_Dictionary_%s.docx' %
                           (Conn, Schemal, time))
        return time

    def exportSchemal(self, Conn=None, Schemal=None):
        tabSet = self.turnOjb.getTableName(ConnName=Conn, SchemalName=Schemal)
        for tableName in tabSet:
            self.document.add_page_break()
            self.document.add_heading('%s : %s' % (tableName[0], tableName[1]),
                                      level=2)
            table = self.document.add_table(rows=1, cols=5)
            table.rows[0].cells[0].text = '字段名'
            table.rows[0].cells[1].text = '类型'
            table.rows[0].cells[2].text = '是否可以为空'
            table.rows[0].cells[3].text = '默认值'
            table.rows[0].cells[4].text = '备注'
            columnSet = self.turnOjb.getTableInfo(ConnName=Conn,
                                                  SchemalName=Schemal,
                                                  TableName='%s' %
                                                  tableName[0])
            for index, column in enumerate(columnSet):
                cells = table.add_row().cells
                cells[0].text = '%s' % column[4]
                cells[1].text = '%s' % column[5]
                cells[2].text = '%s' % column[6]
                cells[3].text = '%s' % column[7]
                cells[4].text = '%s' % column[8]
        self.document.save('./exportData/%s_%s_数据字典.docx' % (Conn, Schemal))
def write_docx(data, filename, **kwargs):
    """ Write a transcript from the .json transcription file. """

    output_filename = Path(filename)

    # Initiate Document
    document = Document()
    # A4 Size
    document.sections[0].page_width = Mm(210)
    document.sections[0].page_height = Mm(297)
    # Font
    font = document.styles["Normal"].font
    font.name = "Calibri"

    # Assign data to variable
    data = data

    # Document title and intro
    title = f"Transcription of {data['jobName']}"
    document.add_heading(title, level=1)
    # Set thresholds for formatting later
    threshold_for_grey = 0.98
    # Intro
    document.add_paragraph(
        "Transcription using AWS Transcribe automatic speech recognition and the 'tscribe' python package."
    )
    document.add_paragraph(
        datetime.datetime.now().strftime("Document produced on %A %d %B %Y at %X.")
    )
    document.add_paragraph()  # Spacing
    document.add_paragraph(
        f"Grey text has less than {int(threshold_for_grey * 100)}% confidence."
    )

    # Get stats
    stats = confidence_stats(data)

    # Display confidence count table
    table = document.add_table(rows=1, cols=3)
    table.style = document.styles["Light List Accent 1"]
    table.alignment = WD_ALIGN_PARAGRAPH.CENTER
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = "Confidence"
    hdr_cells[1].text = "Count"
    hdr_cells[2].text = "Percentage"
    row_cells = table.add_row().cells
    row_cells[0].text = str("98% - 100%")
    row_cells[1].text = str(stats["9.8"])
    row_cells[2].text = str(round(stats["9.8"] / stats["total"] * 100, 2)) + "%"
    row_cells = table.add_row().cells
    row_cells[0].text = str("90% - 97%")
    row_cells[1].text = str(stats["9"])
    row_cells[2].text = str(round(stats["9"] / stats["total"] * 100, 2)) + "%"
    row_cells = table.add_row().cells
    row_cells[0].text = str("80% - 89%")
    row_cells[1].text = str(stats["8"])
    row_cells[2].text = str(round(stats["8"] / stats["total"] * 100, 2)) + "%"
    row_cells = table.add_row().cells
    row_cells[0].text = str("70% - 79%")
    row_cells[1].text = str(stats["7"])
    row_cells[2].text = str(round(stats["7"] / stats["total"] * 100, 2)) + "%"
    row_cells = table.add_row().cells
    row_cells[0].text = str("60% - 69%")
    row_cells[1].text = str(stats["6"])
    row_cells[2].text = str(round(stats["6"] / stats["total"] * 100, 2)) + "%"
    row_cells = table.add_row().cells
    row_cells[0].text = str("50% - 59%")
    row_cells[1].text = str(stats["5"])
    row_cells[2].text = str(round(stats["5"] / stats["total"] * 100, 2)) + "%"
    row_cells = table.add_row().cells
    row_cells[0].text = str("40% - 49%")
    row_cells[1].text = str(stats["4"])
    row_cells[2].text = str(round(stats["4"] / stats["total"] * 100, 2)) + "%"
    row_cells = table.add_row().cells
    row_cells[0].text = str("30% - 39%")
    row_cells[1].text = str(stats["3"])
    row_cells[2].text = str(round(stats["3"] / stats["total"] * 100, 2)) + "%"
    row_cells = table.add_row().cells
    row_cells[0].text = str("20% - 29%")
    row_cells[1].text = str(stats["2"])
    row_cells[2].text = str(round(stats["2"] / stats["total"] * 100, 2)) + "%"
    row_cells = table.add_row().cells
    row_cells[0].text = str("10% - 19%")
    row_cells[1].text = str(stats["1"])
    row_cells[2].text = str(round(stats["1"] / stats["total"] * 100, 2)) + "%"
    row_cells = table.add_row().cells
    row_cells[0].text = str("0% - 9%")
    row_cells[1].text = str(stats["0"])
    row_cells[2].text = str(round(stats["0"] / stats["total"] * 100, 2)) + "%"
    # Add paragraph for spacing
    document.add_paragraph()

    graph = make_graph(stats, str(output_filename.parent))
    document.add_picture(graph, width=Cm(14.64))
    document.paragraphs[-1].alignment = WD_ALIGN_PARAGRAPH.CENTER
    document.add_page_break()

    # Process and display transcript by speaker segments
    table = document.add_table(rows=1, cols=3)
    table.style = document.styles["Light List Accent 1"]
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = "Time"
    hdr_cells[1].text = "Speaker"
    hdr_cells[2].text = "Content"
    # If speaker identification
    if "speaker_labels" in data["results"].keys():

        # A segment is a blob of pronounciation and punctuation by an individual speaker
        for segment in data["results"]["speaker_labels"]["segments"]:

            # If there is content in the segment, add a row, write the time and speaker
            if len(segment["items"]) > 0:
                row_cells = table.add_row().cells
                row_cells[0].text = convert_time_stamp(segment["start_time"])
                row_cells[1].text = str(segment["speaker_label"])

                # For each word in the segment...
                for word in segment["items"]:

                    # Get the word with the highest confidence
                    pronunciations = list(
                        filter(
                            lambda x: x["type"] == "pronunciation",
                            data["results"]["items"],
                        )
                    )
                    word_result = list(
                        filter(
                            lambda x: x["start_time"] == word["start_time"]
                            and x["end_time"] == word["end_time"],
                            pronunciations,
                        )
                    )
                    result = sorted(
                        word_result[-1]["alternatives"], key=lambda x: x["confidence"]
                    )[-1]

                    # Write the word
                    run = row_cells[2].paragraphs[0].add_run(" " + result["content"])
                    if float(result["confidence"]) < threshold_for_grey:
                        font = run.font
                        font.color.rgb = RGBColor(204, 204, 204)

                    # If the next item is punctuation, write it
                    try:
                        word_result_index = data["results"]["items"].index(
                            word_result[0]
                        )
                        next_item = data["results"]["items"][word_result_index + 1]
                        if next_item["type"] == "punctuation":
                            run = (
                                row_cells[2]
                                .paragraphs[0]
                                .add_run(next_item["alternatives"][0]["content"])
                            )
                    except IndexError:
                        pass

    # If channel identification
    elif "channel_labels" in data["results"].keys():

        for word in data["results"]["items"]:

            # Punctuation items do not include a start_time
            if "start_time" not in word.keys():
                continue

            # Identify the channel
            channel = list(
                filter(
                    lambda x: word in x["items"],
                    data["results"]["channel_labels"]["channels"],
                )
            )[0]["channel_label"]

            # If still on the same channel, add the current word to the line
            if table.cell(-1, 1).text == channel:
                current_word = sorted(
                    word["alternatives"], key=lambda x: x["confidence"]
                )[-1]

                run = (
                    table.cell(-1, 2)
                    .paragraphs[0]
                    .add_run(" " + current_word["content"])
                )
                if float(current_word["confidence"]) < threshold_for_grey:
                    font = run.font
                    font.color.rgb = RGBColor(204, 204, 204)

            # Else start a new line
            else:
                current_word = sorted(
                    word["alternatives"], key=lambda x: x["confidence"]
                )[-1]

                row_cells = table.add_row().cells
                row_cells[0].text = convert_time_stamp(word["start_time"])
                row_cells[1].text = channel

                run = row_cells[2].paragraphs[0].add_run(" " + current_word["content"])
                if float(current_word["confidence"]) < threshold_for_grey:
                    font = run.font
                    font.color.rgb = RGBColor(204, 204, 204)

            # If the next item is punctuation, write it
            try:
                word_result_index = data["results"]["items"].index(word)
                next_item = data["results"]["items"][word_result_index + 1]
                if next_item["type"] == "punctuation":
                    run = (
                        row_cells[2]
                        .paragraphs[0]
                        .add_run(next_item["alternatives"][0]["content"])
                    )
            except IndexError:
                pass

    # Else no speaker identification
    else:

        # Start the first row
        row_cells = table.add_row().cells

        # Add words
        for word in data["results"]["items"]:

            # Get the word with the highest confidence
            result = sorted(word["alternatives"], key=lambda x: x["confidence"])[-1]

            # Write the word
            run = row_cells[2].paragraphs[0].add_run(" " + result["content"])
            if float(result["confidence"]) < threshold_for_grey:
                font = run.font
                font.color.rgb = RGBColor(204, 204, 204)

            # If the next item is punctuation, write it
            try:
                word_result_index = data["results"]["items"].index(word)
                next_item = data["results"]["items"][word_result_index + 1]
                if next_item["type"] == "punctuation":
                    run = (
                        row_cells[2]
                        .paragraphs[0]
                        .add_run(next_item["alternatives"][0]["content"])
                    )
            except IndexError:
                pass

    # Formatting transcript table widthds
    widths = (Inches(0.6), Inches(1), Inches(4.5))
    for row in table.rows:
        for idx, width in enumerate(widths):
            row.cells[idx].width = width

    # Save
    document.save(filename)
    with open('keyword_timestamps.json', 'w') as json_file:
        json.dump(wdict, json_file)
예제 #37
0
 def get_blog(self):
     blog_folder_name = self.user + "-blog"
     if not os.path.exists(blog_folder_name):
         os.makedirs(blog_folder_name)
     # 获取日志
     blog_home_elem = self.home_bs.select('table')[2].select(
         'tr')[0].select('td')[0]
     blog_home_url = blog_home_elem.select('a')[0].get('href')
     blog_home_num = blog_home_elem.select('span')[0].getText()
     blog_home_res = self.req.get(blog_home_url, headers=self.headers)
     blog_home_bs = BeautifulSoup(blog_home_res.text, "html.parser")
     # 把日志列表全部找出来,最后一个div是翻页
     is_next = True
     blog_current_bs = blog_home_bs
     while is_next:
         blog_elem_list = blog_current_bs.select('div.list')[0].select(
             'div')
         for blog_elem in blog_elem_list[:-1]:
             blog_url = blog_elem.select('a')[0].get('href')
             # flag=0是分页显示,flag=1是阅读全文
             blog_url = re.sub("flag=0", "flag=1", blog_url)
             blog_res = self.req.get(blog_url, headers=self.headers)
             blog_bs = BeautifulSoup(blog_res.text, "html.parser")
             blog_title = blog_bs.select('div.note')[0].b.getText().strip()
             blog_date = "".join(
                 re.split("\s+",
                          blog_bs.select('div.note')[0].p.getText().strip())
                 [0:2])
             document = Document()
             document.add_heading(blog_title, 0)
             document.add_paragraph(blog_date)
             document.add_heading('正文', level=1)
             # 都是</br>,无法用children选出blog内容,尝试正则的方式
             blog_content_list = blog_bs.select('div.con')[0].contents
             for blog_content in blog_content_list:
                 if blog_content.name == "img":
                     img_url = blog_content.get('src')
                     blog_content = self._get_img_via_url(img_url)
                     # im = Image.open(img_io)  # 通过im.size可以获取图片的尺寸,此处我没有用到
                     # 1024像素=3.413英寸=8.67厘米
                     try:
                         document.add_picture(blog_content, width=Inches(6))
                     except image.exceptions.UnrecognizedImageError:
                         # img无法下载,forbidden403
                         pass
                 elif blog_content.name == "br":
                     pass
                 else:
                     document.add_paragraph(blog_content)
             document.add_heading('好友评论', level=1)
             # 获取评论
             try:
                 blog_comment_div_list = blog_bs.select(
                     'div.list')[0].select('div')
                 # 查看是否有多页评论
                 blog_all_comments_url = blog_bs.select('div.sec')[5].a.get(
                     'href')
                 if blog_all_comments_url:
                     blog_comment_div_list = self._get_all_comments(
                         blog_all_comments_url)
                 self._process_comments(document, blog_comment_div_list)
             except IndexError:
                 # no comments
                 pass
             document.add_page_break()
             blog_file_name = blog_title + '.docx'
             document.save(blog_folder_name + os.sep + blog_file_name)
         is_next = True if blog_elem_list[-1].select('a')[0].get(
             'title') == "下一页" else False
         if is_next:
             blog_next_url = blog_elem_list[-1].select('a')[0].get('href')
             blog_next_res = self.req.get(blog_next_url,
                                          headers=self.headers)
             blog_next_bs = BeautifulSoup(blog_next_res.text, "html.parser")
             blog_current_bs = blog_next_bs
     return blog_folder_name
예제 #38
0
    def __init__(self):
        super(MyWindow, self).__init__()
        file_path, filetype = QFileDialog.getOpenFileName(self, "选择文件", "/", "All Files (*);;Text Files (*.txt)")
        print(file_path)  # 打印文件全部路径(包括文件名和后缀名)
        # 获取文件名
        file_name = re.findall(r'[^\\/:*?"<>|\r\n]+$', file_path)
        file_name = re.findall(r'(.+?)\.xlsx', file_name[0])
        print(file_name[0] + '.xlsx')
        try:
            reload(sys)
            # 开始时间
            startTime = time.time()

            # 读取excel xlsx文件
            wb = load_workbook(file_path)

            # 获取所有sheet页名字
            xl_sheet_names = wb.get_sheet_names()

            # 定位到相应sheet页,[0]为sheet页索引
            xl_sheet = wb.get_sheet_by_name(xl_sheet_names[0])

            # 获取行列数
            excel_row = xl_sheet.max_row
            excel_column = xl_sheet.max_column

            # 创建word文档
            document = Document()

            # 添加标题
            # document.add_heading('xxx', 0)

            table = document.add_table(rows=1, cols=excel_column, style="Table Grid")
            # hdr_cells = table.rows[0].cells
            # for num in range(0, excel_column):
            #     hdr_cells[num].text = u'' + str(xl_sheet.rows[num].value)

            # 取excel第一页第一张表
            i = 0

            # 写入word

            # 将excel表格装入itercars操作
            itercars = iter(xl_sheet.rows)
            # 列名
            hdr_cells = table.rows[0].cells
            for row in xl_sheet.rows:
                for num in range(0, excel_column):
                    hdr_cells[num].text = u'' + str(row[num].value)
                break

            # 进入第二行开始循环插入
            next(itercars)
            for row in itercars:
                # 添加行数
                row_cells = table.add_row().cells
                for num in range(0, excel_column):
                    content = str(row[num].value)
                    content = "" if content == "None" else content
                    row_cells[num].text = u'' + content

            document.add_page_break()
            # document.save('demo.docx')
            docx_path = file_path.replace('xlsx', 'docx')
            document.save(docx_path)
            title = g.msgbox(msg="                                     成功!", title="Success", ok_button="确定")
        except Exception as err:
            print(err)
            title = g.msgbox(msg="               生成失败:" + err, title="Error", ok_button="确定")
예제 #39
0
class wordSave:
    def __init__(self):
        self.makeTitul()
        self.document = Document()
        self.helpDict = {
            "paragraph": self.addLine,
            "heading": self.addHeading,
            "list": self.addList,
            "link": self.addLink
        }

    def addPageBreak(self):
        self.document.add_page_break()

    def addCode(self, code):
        par = self.document.add_paragraph("")
        for line in code:
            par.add_run(line).font.size = Pt(10)

    def makeTitul(self):
        tpl = DocxTemplate('patternTitle.docx')
        self.js = json.load(open('settings.json'))
        context = {
            'cathedra':
            RichText(self.js['cathedra'].encode('cp1251', 'ignore')),
            'discipline':
            RichText(self.js['discipline'].encode('cp1251', 'ignore')),
            'theme':
            RichText(self.js['theme'].encode('cp1251', 'ignore')),
            'group':
            RichText(self.js['group'].encode('cp1251', 'ignore')),
            'name':
            RichText(self.js['name'].encode('cp1251', 'ignore')),
            'teacher':
            RichText(self.js['teacher'].encode('cp1251', 'ignore')),
            'initialData':
            RichText(self.js['initialData'].encode('cp1251', 'ignore')),
            'content':
            RichText(self.js['content'].encode('cp1251', 'ignore')),
            'numberPages ':
            RichText(self.js['numberPages'].encode('cp1251', 'ignore')),
            'surrender':
            RichText(self.js['surrender'].encode('cp1251', 'ignore')),
            'numberPages':
            RichText(self.js['numberPages'].encode('cp1251', 'ignore')),
            'extradition':
            RichText(self.js['extradition'].encode('cp1251', 'ignore')),
            'protection':
            RichText(self.js['protection'].encode('cp1251', 'ignore')),
            'annotation':
            RichText(self.js['annotation'].encode('cp1251', 'ignore')),
            'summary':
            RichText(self.js['summary'].encode('cp1251', 'ignore')),
            'introduction':
            RichText(self.js['introduction'].encode('cp1251', 'ignore')),
        }
        tpl.render(context)
        tpl.save('compileTitul.docx')

    def addLine(self, line):
        self.document.add_paragraph(line)

    def addHeadCode(self, line):
        self.document.add_heading().add_run(line).font.size = Pt(20)

    # def addFromDict(self,dict):

    def reform(self, mass, line, tag):
        # line.style=self.document.styles['Normal']
        for element in mass:
            x = line.add_run(element["line"])
            if tag in self.js['formatter']:
                x.font.size = Pt(self.js['formatter'][tag]['size'])
            x.font.bold = element["bold"]
            x.font.italic = element["italic"]
            x.font.underline = element["underline"]

    def addHeading(self, mass, lvl=1):
        line = self.document.add_heading('', level=lvl)
        self.reform(mass, line, "h" + str(lvl))

    # style='IntenseQuote'-цитата
    # style='ListBullet'-точки
    # style='ListNumber'-цифры

    def addList(self, mass):
        line = self.document.add_paragraph('', style='ListBullet')
        self.reform(mass, line, "list")

    def checkInnerInfo(self, mass, line):
        for elem in mass:
            if elem['type'] == "img":
                self.addPicture([elem])
            if elem['type'] == "link":
                if elem['line'] == "":
                    self.add_hyperlink(line, elem['src'], " [url]")
                else:
                    self.add_hyperlink(line, elem['src'], elem['line'])

    def addLink(self, mass):
        line = self.document.add_paragraph('')
        self.checkInnerInfo(mass, line)

    def add_hyperlink(self, paragraph, url, text):
        part = paragraph.part
        r_id = part.relate_to(url,
                              docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK,
                              is_external=True)
        hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink')
        hyperlink.set(
            docx.oxml.shared.qn('r:id'),
            r_id,
        )
        new_run = docx.oxml.shared.OxmlElement('w:r')
        rPr = docx.oxml.shared.OxmlElement('w:rPr')
        new_run.append(rPr)
        new_run.text = text
        hyperlink.append(new_run)
        paragraph._p.append(hyperlink)
        return hyperlink

    def addParagraph(self, mass):
        line = self.document.add_paragraph('')
        self.reform(mass, line, "p")
        self.checkInnerInfo(mass, line)

    def getImgByUrl(self, url):
        response = requests.get(url, stream=True)
        return io.BytesIO(response.content)

    def addPicture(self, mass):
        for elem in mass:
            if elem['type'] == 'img':
                url = elem["src"]
                try:
                    self.document.add_picture(self.getImgByUrl(url))
                except Exception:
                    print("bad image url")
            else:
                if elem['type'] == 'link':
                    self.addLink([elem])
                else:
                    self.addParagraph([elem])

    def saveFile(self):
        self.document.save('ReadyProject.docx')
예제 #40
0
def new_doc(userinfo, host, school_name, author, frequency, ip1, ip2, port1,
            port2, username1, username2, password1, password2, time, db_name,
            db_name_output, oracle_base, cpu1, cpu2, memory1, memory2, swap1,
            swap2, gateway1, gateway2, version, os_version, timezone1,
            timezone2, syslog1, syslog2, filesystem1, filesystem2, cluster,
            cluster_alert1, cluster_alert2, crsdlog1, crsdlog2, cssdlog1,
            cssdlog2, ocr_backup, asm_sql, asm_alert1, asm_alert2,
            database_version_sql, sga_sql, controlfile_sql, redolog_sql,
            tablespace_sql, virus_sql, listener1, listener2, listener_log1,
            listener_log2, doc_path):  #新建一个word文档,写入汇总表的数据
    document = Document()
    document.styles['Title'].font.name = u'Microsoft YaHei'
    document.styles['Title'].font.size = Pt(26)
    document.styles['Title'].font.underline = False
    document.styles['Title']._element.rPr.rFonts.set(qn('w:eastAsia'),
                                                     u'Microsoft YaHei')
    document.styles['Title'].font.color.rgb = RGBColor(0x00, 0x00, 0x00)
    document.styles['Normal'].font.name = u'等线 Light'
    document.styles['Normal'].font.size = Pt(9)
    document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'),
                                                      u'等线 Light')
    document.styles['Normal'].paragraph_format.left_indent = Inches(0)
    #document.styles['Normal'].paragraph_format.first_line_indent = Inches(0.25)
    #document.styles['Normal'].paragraph_format.space_before = Pt(8)
    #document.styles['Normal'].paragraph_format.space_after = Pt(8)
    #document.styles['Normal'].paragraph_format.line_spacing = 1
    document.styles['Heading 1'].font.name = u'等线 Light'
    document.styles['Heading 1'].font.size = Pt(22)
    document.styles['Heading 1']._element.rPr.rFonts.set(
        qn('w:eastAsia'), u'等线 Light')
    document.styles['Heading 1'].font.color.rgb = RGBColor(0x00, 0x00, 0x00)
    #document.styles['Heading 1'].next_paragraph_style = document.styles['Normal']
    document.styles['Heading 2'].font.name = u'等线 Light'
    document.styles['Heading 2'].font.size = Pt(16)
    document.styles['Heading 2'].font.color.rgb = RGBColor(0x00, 0x00, 0x00)
    document.styles['Heading 2']._element.rPr.rFonts.set(
        qn('w:eastAsia'), u'等线 Light')
    document.styles['Heading 3'].font.name = u'等线 Light'
    document.styles['Heading 3'].font.size = Pt(14)
    document.styles['Heading 3'].font.color.rgb = RGBColor(0x00, 0x00, 0x00)
    document.styles['Heading 3']._element.rPr.rFonts.set(
        qn('w:eastAsia'), u'等线 Light')
    #document.add_heading(u'1 巡检说明',level=1)
    document.add_paragraph(
        u'\n\n\n\n%s\n\nOracle数据库\n\n巡\n\n检\n\n报\n\n告' % school_name,
        style='Title').paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    document.add_paragraph(
        u'        版权声明和保密须知\n        本文中出现的任何文字描述、文档格式、插图、照片、方法、过程等内容,除另有特别注明,版权均属江苏金智教育信息股份有限公司所有,受到有关产权及版权法保护。任何单位和个人未经江苏金智教育信息股份有限公司的书面授权许可,不得复制或引用本文件的任何片段,无论通过电子形式或非电子形式。\n        Copyright @ 2018 江苏金智教育信息股份有限公司 版权所有',
        style='Normal')
    document.add_page_break()
    document.add_heading(u'文档控制', level=1)
    document.add_paragraph(
        u'        此文档仅供%s与江苏金智教育信息股份有限公司审阅,不得向与此无关的个人或机构传阅或复制。' % school_name,
        style='Normal')
    document.add_heading(u'修改记录', level=1)
    record_output = document.add_table(1, 4, style="Table Grid")
    record_output_cells = record_output.rows[0].cells
    record_output_cells[0].text = u'日期'
    record_output_cells[1].text = u'作者'
    record_output_cells[2].text = u'版本'
    record_output_cells[3].text = u'修改记录'
    cells = record_output.add_row().cells
    cells[0].text = time
    cells[1].text = author
    cells[2].text = u'V1.0'
    cells[3].text = u'起草'
    cells = record_output.add_row().cells
    document.add_heading(u'审阅记录', level=1)
    review_output = document.add_table(1, 2, style="Table Grid")
    review_output_cells = review_output.rows[0].cells
    review_output_cells[0].text = u'姓名'
    review_output_cells[1].text = u'职务'
    cells = review_output.add_row().cells
    cells[0].text = u'胡楠'
    cells[1].text = u'数据库服务部经理'
    document.add_heading(u'相关文档', level=1)
    document.add_paragraph(u'        无')
    document.add_page_break()
    document.add_paragraph(u'        添加目录')
    document.add_page_break()
    document.add_heading(u'1 巡检说明', level=1)
    document.add_heading(u'1.1 基本信息', level=2)
    document.add_paragraph(u'本次总共对%s' % school_name + u'%s套Oracle数据库进行巡检。' %
                           (len(db_name) - 1),
                           style='Normal')
    document.add_paragraph(u'巡检时间:' + str(time))
    document.add_paragraph(u'巡检方式:■远程巡检  □现场巡检。')
    document.add_paragraph(u'巡检的数据库列表如下:')
    info_output = document.add_table(1, 4, style="Medium Grid 3 Accent 1")
    info_output_cells = info_output.rows[0].cells
    info_output_cells[0].text = u'数据库名及版本'
    info_output_cells[1].text = u'IP地址'
    info_output_cells[2].text = u'操作系统'
    info_output_cells[3].text = u'描述'
    for q in db_name:
        if q.strip():
            cells = info_output.add_row().cells
            cells[0].text = str(q) + '\n' + 'Oracle' + ' ' + str(
                version).replace('\n', '')
            cells[1].text = str(ip1) + '\n' + str(ip2)
            cells[2].text = str(os_version[0]) + '\n' + str(os_version[2])
            cells[3].text = ''
        else:
            pass
    document.add_heading(u'1.2 巡检小结', level=2)
    summary_output = document.add_table(1, 3, style="Medium Grid 3 Accent 1")
    summary_output_cells = summary_output.rows[0].cells
    summary_output_cells[0].text = u'类别'
    summary_output_cells[1].text = u'检查细项'
    summary_output_cells[2].text = u'结果'
    summary_output_cells[0].width = Inches(0.2)
    summary_output_cells[1].width = Inches(1.0)
    summary_output_cells[2].width = Inches(4.0)
    cells = summary_output.add_row().cells
    cells[0].text = u'操作系统巡检'
    cells[1].text = u'操作系统基本信息'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u''
    cells[1].text = u'操作系统时区'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u''
    cells[1].text = u'操作系统日志'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u''
    cells[1].text = u'操作系统磁盘空间'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u'集群巡检'
    cells[1].text = u'集群资源状态'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u''
    cells[1].text = u'集群告警日志'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u''
    cells[1].text = u'集群CRS日志'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u''
    cells[1].text = u'集群CSS日志'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u''
    cells[1].text = u'OCR自动备份'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u'ASM巡检'
    cells[1].text = u'磁盘组信息'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u''
    cells[1].text = u'ASM告警日志'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u'数据库巡检'
    cells[1].text = u'数据库版本'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u''
    cells[1].text = u'SGA组成'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u''
    cells[1].text = u'控制文件'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u''
    cells[1].text = u'在线重做日志'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u''
    cells[1].text = u'表空间管理'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u''
    cells[1].text = u'已知木马检测'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u''
    cells[1].text = u'数据库告警日志'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u'网络巡检'
    cells[1].text = u'监听状态'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u''
    cells[1].text = u'监听日志'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u'备份策略评估'
    cells[1].text = u'RMAN物理备份'
    cells[2].text = u'■通过  □警告  □失败'
    cells = summary_output.add_row().cells
    cells[0].text = u''
    cells[1].text = u'逻辑备份'
    cells[2].text = u'■通过  □警告  □失败'
    document.add_heading(u'1.3 问题点与调整', level=2)
    document.add_paragraph(u'        根据本次巡检结果,目前Oracle数据库环境存在以下几个问题点:',
                           style='Normal')
    document.add_heading(u'1.4 后续建议', level=2)
    document.add_paragraph(u'        针对巡检结果,后续建议:', style='Normal')
    document.add_heading(u'2 巡检细项', level=1)
    document.add_heading(u'2.1 操作系统巡检', level=2)
    document.add_heading(u'2.1.1 操作系统基本信息', level=3)
    sysinfo_output = document.add_table(1, 5, style="Medium Grid 3 Accent 1")
    sysinfo_output_cells = sysinfo_output.rows[0].cells
    sysinfo_output_cells[0].text = u'主机名'
    sysinfo_output_cells[1].text = u'CPU配置'
    sysinfo_output_cells[2].text = u'物理内存'
    sysinfo_output_cells[3].text = u'交换分区'
    sysinfo_output_cells[4].text = u'默认网关'
    cells = sysinfo_output.add_row().cells
    cells[0].text = str(hostname1)
    cells[1].text = str(cpu1) + ' ' + 'Processor(s)'
    cells[2].text = str(int(memory1) / 1024) + 'MB'
    cells[3].text = str(int(swap1) / 1024) + 'MB'
    cells[4].text = str(gateway1)
    cells = sysinfo_output.add_row().cells
    cells[0].text = str(hostname2)
    cells[1].text = str(cpu2) + ' ' + 'Processor(s)'
    cells[2].text = str(int(memory2) / 1024) + 'MB'
    cells[3].text = str(int(swap2) / 1024) + 'MB'
    cells[4].text = str(gateway2)
    #输出节点一时区
    document.add_heading(u'2.1.2 操作系统时间与时区', level=3)
    document.add_paragraph(
        u'        数据库服务器的操作系统时区与时间设置,要符合本地时区时间设置。否则对部分时间敏感业务会造成一定的影响。譬如,教务选课系统、一卡通系统等。',
        style='Normal')
    p_total = document.add_paragraph()
    r_total = p_total.add_run(u'节点一时间与时区:')
    r_total.font.bold = True
    p_total = document.add_paragraph()
    p_total = p_total.add_run(timezone1)
    #输出节点二时区
    p_total = document.add_paragraph()
    r_total = p_total.add_run(u'节点二时间与时区:')
    r_total.font.bold = True
    p_total = document.add_paragraph()
    p_total = p_total.add_run(timezone2)
    document.add_paragraph(u'结论:■正常  □不正常。', style='Normal')
    #输出节点一操作系统文件系统使用率
    document.add_heading(u'2.1.3 操作系统磁盘空间', level=3)
    p_total = document.add_paragraph()
    r_total = p_total.add_run(u'节点一文件系统使用率:')
    r_total.font.bold = True
    filesystem1_output = document.add_table(1,
                                            6,
                                            style="Medium Grid 3 Accent 1")
    filesystem1_output_cells = filesystem1_output.rows[0].cells
    filesystem1_output_cells[0].text = u'Filesystem'
    filesystem1_output_cells[1].text = u'Size'
    filesystem1_output_cells[2].text = u'Used'
    filesystem1_output_cells[3].text = u'Avail'
    filesystem1_output_cells[4].text = u'Use%'
    filesystem1_output_cells[5].text = u'Mounted on'
    for i in range(1, len(filesystem1) / 6):
        cells = filesystem1_output.add_row().cells
        cells[0].text = str(filesystem1[i * 6 + 1])
        cells[1].text = str(filesystem1[i * 6 + 2])
        cells[2].text = str(filesystem1[i * 6 + 3])
        cells[3].text = str(filesystem1[i * 6 + 4])
        cells[4].text = str(filesystem1[i * 6 + 5])
        cells[5].text = str(filesystem1[i * 6 + 6])
#输出节点二操作系统文件系统使用率
    p_total = document.add_paragraph()
    r_total = p_total.add_run(u'节点二文件系统使用率:')
    r_total.font.bold = True
    filesystem2_output = document.add_table(1,
                                            6,
                                            style="Medium Grid 3 Accent 1")
    filesystem2_output_cells = filesystem2_output.rows[0].cells
    filesystem2_output_cells[0].text = u'Filesystem'
    filesystem2_output_cells[1].text = u'Size'
    filesystem2_output_cells[2].text = u'Used'
    filesystem2_output_cells[3].text = u'Avail'
    filesystem2_output_cells[4].text = u'Use%'
    filesystem2_output_cells[5].text = u'Mounted on'
    for i in range(1, len(filesystem2) / 6):
        cells = filesystem2_output.add_row().cells
        cells[0].text = str(filesystem2[i * 6 + 1])
        cells[1].text = str(filesystem2[i * 6 + 2])
        cells[2].text = str(filesystem2[i * 6 + 3])
        cells[3].text = str(filesystem2[i * 6 + 4])
        cells[4].text = str(filesystem2[i * 6 + 5])
        cells[5].text = str(filesystem2[i * 6 + 6])
    document.add_paragraph(u'结论:■正常  □不正常。', style='Normal')
    #输出节点一操作系统日志
    document.add_heading(u'2.1.4 操作系统日志', level=3)
    document.add_paragraph(
        u'        操作系统日志记录了操作系统运行相关的日志信息。当硬件发生变更、软件及操作系统服务运行异常时,系统日志均会予以记录。本次巡检,对最近%s个月的操作系统运行日志予以检查。'
        % frequency,
        style='Normal')
    p_total = document.add_paragraph()
    r_total = p_total.add_run(u'节点一操作系统日志:')
    r_total.font.bold = True
    p_total = document.add_paragraph()
    p_total = p_total.add_run(syslog1)
    #输出节点二操作系统日志
    p_total = document.add_paragraph()
    r_total = p_total.add_run(u'节点二操作系统日志:')
    r_total.font.bold = True
    p_total = document.add_paragraph()
    p_total = p_total.add_run(syslog2)
    document.add_paragraph(u'结论:■正常  □不正常。', style='Normal')
    #输出集群资源状态
    document.add_heading(u'2.2 集群巡检', level=2)
    document.add_heading(u'2.2.1 集群资源状态', level=3)
    p_total = document.add_paragraph()
    p_total = p_total.add_run(cluster)
    document.add_paragraph(u'结论:■正常  □不正常。', style='Normal')
    #输出节点一集群告警日志
    document.add_heading(u'2.2.2 集群告警日志', level=3)
    document.add_paragraph(
        u'        集群告警日志包含了集群系统级别的错误与报警,需要对近期发现的集群错误进行检查与分析。本次巡检时,在对集群两个节点的alert日志进行分析,发现最近%s个月,集群告警日志无异常记录。'
        % frequency,
        style='Normal')
    p_total = document.add_paragraph()
    r_total = p_total.add_run(u'节点一集群告警日志:')
    r_total.font.bold = True
    p_total = document.add_paragraph()
    p_total = p_total.add_run(cluster_alert1)
    #输出节点二集群告警日志
    p_total = document.add_paragraph()
    r_total = p_total.add_run(u'节点二集群告警日志:')
    r_total.font.bold = True
    p_total = document.add_paragraph()
    p_total = p_total.add_run(cluster_alert2)
    document.add_paragraph(u'结论:■正常  □不正常。', style='Normal')
    #输出节点一集群crs日志
    document.add_heading(u'2.2.3 集群CRS日志', level=3)
    document.add_paragraph(
        u'        集群CRS日志包含了集群CRS资源的错误与告警,需要对近期发现的集群资源错误进行检查与分析。本次巡检,对集群两个节点的CRS日志进行分析,发现最近%s个月,集群CRS日志无异常记录。'
        % frequency,
        style='Normal')
    p_total = document.add_paragraph()
    r_total = p_total.add_run(u'节点一crs日志:')
    r_total.font.bold = True
    p_total = document.add_paragraph()
    p_total = p_total.add_run(crsdlog1)
    #输出节点二集群crs日志
    p_total = document.add_paragraph()
    r_total = p_total.add_run(u'节点二crs日志:')
    r_total.font.bold = True
    p_total = document.add_paragraph()
    p_total = p_total.add_run(crsdlog2)
    document.add_paragraph(u'结论:■正常  □不正常。', style='Normal')
    #输出节点一集群css日志
    document.add_heading(u'2.2.4 集群CSS日志', level=3)
    document.add_paragraph(
        u'        集群CSS日志包含了集群节点通信、同步的错误与告警,需要对近期发现的集群节点通信、同步错误进行检查与分析。本次巡检时,在对集群两个节点的CSS日志进行分析,发现最近%s个月,集群CSS日志无异常记录。'
        % frequency,
        style='Normal')
    p_total = document.add_paragraph()
    r_total = p_total.add_run(u'节点一css日志:')
    r_total.font.bold = True
    p_total = document.add_paragraph()
    p_total = p_total.add_run(cssdlog1)
    #输出节点二集群css日志
    p_total = document.add_paragraph()
    r_total = p_total.add_run(u'节点二css日志:')
    r_total.font.bold = True
    p_total = document.add_paragraph()
    p_total = p_total.add_run(cssdlog2)
    document.add_paragraph(u'结论:■正常  □不正常。', style='Normal')
    #输出ocr备份状态
    document.add_heading(u'2.2.5 OCR自动备份状态', level=3)
    document.add_paragraph(u'        巡检过程中,对OCR自动备份进行检查。本次巡检,OCR自动备份正常',
                           style='Normal')
    p_total = document.add_paragraph()
    p_total = p_total.add_run(ocr_backup)
    document.add_paragraph(u'结论:■正常  □不正常。', style='Normal')
    document.save(doc_path)
    #输出ASM磁盘组信息
    document = Document(doc_path)
    document.add_heading(u'2.3 ASM巡检', level=2)
    document.add_paragraph(u'        本节主要对ASM实例运行状态、磁盘组的配置情况进行详细描述与检查。',
                           style='Normal')
    document.add_heading(u'2.3.1 磁盘组信息', level=3)
    document.save(doc_path)
    get_asm(userinfo, host, db_name, asm_sql)
    document = Document(doc_path)
    document.add_paragraph(u'结论:■正常  □不正常。', style='Normal')
    document.save(doc_path)
    #输出节点一ASM ALERT告警日志
    document = Document(doc_path)
    document.add_heading(u'2.3.2 ASM告警日志', level=3)
    document.add_paragraph(u'        检查了集群ASM实例最近%s个月的alert告警日志,告警日志无异常记录。' %
                           frequency,
                           style='Normal')
    p_total = document.add_paragraph()
    r_total = p_total.add_run(u'节点一ASM ALERT告警日志:')
    r_total.font.bold = True
    p_total = document.add_paragraph()
    p_total = p_total.add_run(asm_alert1)
    #输出节点二ASM ALERT告警日志
    p_total = document.add_paragraph()
    r_total = p_total.add_run(u'节点二ASM ALERT告警日志:')
    r_total.font.bold = True
    p_total = document.add_paragraph()
    p_total = p_total.add_run(asm_alert2)
    document.add_paragraph(u'结论:■正常  □不正常。', style='Normal')
    document.save(doc_path)
    #输出数据库版本
    document = Document(doc_path)
    document.add_heading(u'2.4 数据库巡检', level=2)
    document.add_paragraph(u'        该部分详细阐述了数据库%s的主要结构。' % db_name_output +
                           u'注:以下部分,若没有特殊说明,均表示%s个数据库配置一致。' %
                           (len(db_name) - 1),
                           style='Normal')
    document.add_heading(u'2.4.1 数据库版本', level=3)
    document.save(doc_path)
    get_database_version(userinfo, host, db_name, database_version_sql)
    document = Document(doc_path)
    document.add_paragraph(u'结论:■正常  □不正常。', style='Normal')
    document.save(doc_path)
    #输出sga
    document = Document(doc_path)
    document.add_heading(u'2.4.2 SGA组成', level=3)
    document.add_paragraph(u'        以下是数据库%s的SGA内存参数设置信息:' % db_name_output,
                           style='Normal')
    document.save(doc_path)
    get_sga(userinfo, host, db_name, sga_sql)
    document = Document(doc_path)
    document.add_paragraph(u'结论:■正常  □不正常。', style='Normal')
    document.save(doc_path)
    #输出控制文件信息
    document = Document(doc_path)
    document.add_heading(u'2.4.3 控制文件', level=3)
    document.add_paragraph(u'        以下是数据库%s的控制文件相关信息:' % db_name_output,
                           style='Normal')
    document.save(doc_path)
    get_controlfile(userinfo, host, db_name, controlfile_sql)
    document = Document(doc_path)
    document.add_paragraph(u'结论:■正常  □不正常。', style='Normal')
    document.save(doc_path)
    #输出在线重做日志信息
    document = Document(doc_path)
    document.add_heading(u'2.4.4 在线重做日志', level=3)
    document.add_paragraph(u'        以下是数据库%s的在线重做日志相关信息:' % db_name_output,
                           style='Normal')
    document.save(doc_path)
    get_redolog(userinfo, host, db_name, redolog_sql)
    document = Document(doc_path)
    document.add_paragraph(u'结论:■正常  □不正常。', style='Normal')
    document.save(doc_path)
    #输出表空间使用率
    document = Document(doc_path)
    document.add_heading(u'2.4.5 表空间管理', level=3)
    document.add_paragraph(
        u'        以下是数据库表空间的管理和使用情况。在ORACLE 9i之后除了系统表空间,其他的表空间的空间段管理方式推荐为LOCAL。\n        临时表空间用于存放临时段。为了维护数据库的性能,临时表空间的维护方法有别于其他一般表空间。缺省情况下,所有表空间都创建为PERMANENT。所以在创建临时段时,需要保证表空间类型为TEMPORARY。由于这些表空间中的排序段不被清除,所以减少了空间事务争夺,同时减少了SMON对于CPU的使用率。\n        由于表空间的extent 出现了local management 方式,对表空间采用了位图管理,更利于空间的使用及回收管理。',
        style='Normal')
    document.save(doc_path)
    get_tablespace(userinfo, host, db_name, tablespace_sql)
    document = Document(doc_path)
    document.add_paragraph(u'结论:■正常  □不正常。', style='Normal')
    document.save(doc_path)
    #输出病毒检查结果
    document = Document(doc_path)
    document.add_heading(u'2.4.6 已知木马检测', level=3)
    document.add_paragraph(
        u'        根据各大安全网站公布的数据,定期更新数据库病毒检测库,对已知的数据库病毒程序进行检查,本次巡检数据库安全情况如下:',
        style='Normal')
    document.save(doc_path)
    get_virus(userinfo, host, db_name, virus_sql)
    document = Document(doc_path)
    document.add_paragraph(u'结论:■正常  □不正常。', style='Normal')
    document.save(doc_path)
    #输出节点一数据库alert告警日志
    document = Document(doc_path)
    document.add_heading(u'2.4.7 数据库告警日志', level=3)
    document.add_paragraph(
        u'        数据库alert告警日志包含了系统级别的错误与告警,需要对发现的ORA错误进行检查与分析。最近%s个月告警日志无异常记录。'
        % frequency,
        style='Normal')
    document.save(doc_path)
    get_database_alert1(oracle_base, db_name, ip1, port1, username1, password1)
    #输出节点二数据库alert告警日志
    get_database_alert2(oracle_base, db_name, ip2, port2, username2, password2)
    document = Document(doc_path)
    document.add_paragraph(u'结论:■正常  □不正常。', style='Normal')
    document.save(doc_path)
    #输出节点一监听状态
    document = Document(doc_path)
    document.add_heading(u'2.5 网络巡检', level=2)
    document.add_paragraph(u'        本节主要对数据库网络、监听的运行情况予以检查。', style='Normal')
    document.add_heading(u'2.5.1 监听状态', level=3)
    document.add_paragraph(u'        巡检过程中,对监听状态进行检查,结果显示,两个节点的监听状态及服务均正常。',
                           style='Normal')
    p_total = document.add_paragraph()
    r_total = p_total.add_run(u'节点一监听状态:')
    r_total.font.bold = True
    p_total = document.add_paragraph()
    p_total = p_total.add_run(listener1)
    #输出节点二监听状态
    p_total = document.add_paragraph()
    r_total = p_total.add_run(u'节点二监听状态:')
    r_total.font.bold = True
    p_total = document.add_paragraph()
    p_total = p_total.add_run(listener2)
    document.add_paragraph(u'结论:■正常  □不正常。', style='Normal')
    #输出节点一监听日志
    document.add_heading(u'2.5.2 监听日志', level=3)
    document.add_paragraph(
        u'        巡检过程中,对集群两个节点的监听日志予以检查。检查发现,最近%s个月两个节点的监听日志无异常记录。' %
        frequency,
        style='Normal')
    p_total = document.add_paragraph()
    r_total = p_total.add_run(u'节点一监听日志:')
    r_total.font.bold = True
    p_total = document.add_paragraph()
    p_total = p_total.add_run(listener_log1)
    #输出节点二监听日志
    p_total = document.add_paragraph()
    r_total = p_total.add_run(u'节点二监听日志')
    r_total.font.bold = True
    p_total = document.add_paragraph()
    p_total = p_total.add_run(listener_log2)
    document.add_paragraph(u'结论:■正常  □不正常。', style='Normal')
    #保存word
    document.add_heading(u'2.6 数据库备份策略评估', level=2)
    document.add_paragraph(u'        本节主要对数据库的备份与恢复策略进行检查与评估。', style='Normal')
    backup_output = document.add_table(1, 8, style="Medium Grid 3 Accent 1")
    backup_output.alignment = WD_TABLE_ALIGNMENT.LEFT
    backup_output.allow_autofit = False
    backup_output_cells = backup_output.rows[0].cells
    backup_output_cells[0].text = u'数据库用途'
    backup_output_cells[1].text = u'数据库名'
    backup_output_cells[2].text = u'物理备份情况(含异地备份)'
    backup_output_cells[3].text = u'物理备份保留周期'
    backup_output_cells[4].text = u'物理备份数据可恢复时间段'
    backup_output_cells[5].text = u'逻辑备份情况(含异地备份)'
    backup_output_cells[6].text = u'逻辑备份保留周期'
    backup_output_cells[7].text = u'逻辑备份数据可恢复时间段'
    backup_output_cells[0].width = Inches(1.0)
    for i in range(0, (len(db_name) - 1)):
        cells = backup_output.add_row().cells
        cells[0].text = ''
        cells[1].text = str(db_name[i])
        cells[2].text = u'■正常\n□警告\n□异常'
        cells[3].text = u'本地备份保留14天,异地备份保留14天'
        cells[4].text = u'可以恢复到14天之内任意时间点'
        cells[5].text = u'■正常\n□警告\n□异常'
        cells[6].text = u'本地备份保留7天,异地备份保留7天'
        cells[7].text = u'可以恢复到7天内做逻辑备份的时间点'
    document.save(doc_path)
예제 #41
0
def Append_Files(file_names, num, fixed_dir, part_no, model_no_names,
                 cap_names, chassis_names, cntrllr_names, fw_type_temp,
                 fw_no_names, test_name, detection_matrix):

    rf = report_functions.Report_Functions

    document = Document(r'' + str(fixed_dir) + '\\' + str(part_no) +
                        str(test_name) + '.docx')
    document.add_page_break()

    ###################################################
    #
    #   A loop to append/add multiple files to Modified
    #   Word template
    #
    ###################################################
    for f in range(int(num)):

        progress = (round((float(100 / int(num)) * f), 2))
        # to show Report Progress
        print('\nReport Progess: ', progress, '%\n')

        m_data = pandas.read_csv(open(r'' + file_names[f] + '_Modified.csv'),
                                 header=None)
        md = np.array(m_data)

        ###################################################
        #
        #  Converting numbers to 1 decimal place
        #
        ###################################################
        for j in range(4, 8):
            for i in range(1, len(md[:, 1])):

                temp = md[i, j]
                precise_d = float(temp)
                precise_d = round(precise_d, 1)
                md[i, j] = str(precise_d)

        ###################################################
        #
        #  Appending files from the section of Modified
        #  word template with all Formatting.
        #
        ###################################################

        # If change heading for SSD-HDD
        if detection_matrix[f] == 1:
            drive_type_text = 'SSD '
        else:
            drive_type_text = 'HDD '

        document.add_heading(
            'Performance Results - chassis ' + str(f + 1) + '\nModel: ' +
            model_no_names[f] + ', ' + cap_names[f] + ' in ' +
            chassis_names[f] + '/' + cntrllr_names[f] + ' chassis, ' +
            str(drive_type_text) + str(fw_type_temp) + ' FW: ' +
            fw_no_names[f],
            level=3)

        section = document.sections[-1]
        # last section in document
        section.start_type = WD_SECTION.NEW_PAGE

        section.top_margin = Inches(0.3)
        section.bottom_margin = Inches(0)

        section.left_margin = Inches(0.5)
        section.right_margin = Inches(0.5)

        r = len(md[:, 0])
        c = len(md[0, :])

        table_style = document.styles["Normal"]
        table_font = table_style.font
        table = document.add_table(rows=r, cols=c)
        table.alignment = WD_TABLE_ALIGNMENT.CENTER

        table.autofit = False
        rf.set_column_width(table.columns[0], Cm(1.3))  #alignment
        rf.set_column_width(table.columns[1], Cm(2.3))  #drive
        rf.set_column_width(table.columns[2], Cm(3.8))  #target name
        rf.set_column_width(table.columns[3], Cm(2.8))  #acess spec
        rf.set_column_width(table.columns[4], Cm(1.5))  #IOps
        rf.set_column_width(table.columns[5], Cm(1.4))  #MBps
        rf.set_column_width(table.columns[6], Cm(1.6))  #Avg. Latency
        rf.set_column_width(table.columns[7], Cm(1.6))  #Max. Latency
        rf.set_column_width(table.columns[8], Cm(1.1))  #QD
        rf.set_column_width(table.columns[9], Cm(1.3))  #Read Errors
        rf.set_column_width(table.columns[10], Cm(1.3))  #Write Errors

        table.style = 'Table Grid'

        for i in range(r):
            for j in range(c):
                table_font.size = Pt(9)

                hdr_cells = table.rows[i].cells
                if i == 0:
                    hdr_cells[j].text = md[i, j]

                else:

                    hdr_cells[j].text = md[i, j]

        document.add_picture(r'' + file_names[f] + '_Modified.csv_Plot_1.png',
                             width=Inches(8),
                             height=Inches(9))

        last_paragraph = document.paragraphs[-1]
        last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

        document.add_picture(r'' + file_names[f] + '_Modified.csv_Plot_2.png',
                             width=Inches(7.5),
                             height=Inches(9.3))

        last_paragraph = document.paragraphs[-1]
        last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

        document.save(r'' + str(fixed_dir) + '\\' + str(part_no) +
                      str(test_name) + '.docx')

        # remove temporary generated document

        os.remove(r'' + file_names[f] + '_Modified.csv')
        os.remove(r'' + file_names[f] + '_Modified.csv_Plot_1.png')
        os.remove(r'' + file_names[f] + '_Modified.csv_Plot_2.png')

    os.remove(r'' + str(fixed_dir) + '\\temp_doc.docx')
    print('\nYour Report is ready!\n')
예제 #42
0
def write4answersheet(answer_sheet_data):
    '''
    answer_sheet_data = {
        "name": paper_data["name"],
        "main_title": "{}-答题卡".format(paper_data["main_title"]),
        "testee": paper_data["testee"],
        "sheet": answer_sheet
    }
    answer_sheet[key].append({
                "q_no": ques_no,
                "pic_in_card": pic_in_card,
                "options": [v["key"] for v in options if v.get("key")],
                "subques_len": len(subquestions) if subquestions else 0
            })
    '''
    sheet = answer_sheet_data.get('sheet', {})
    sheet_name = answer_sheet_data.get('name')
    main_title = answer_sheet_data.get('main_title')
    answer_path = r'nile/static/mark_pic/answersheet.docx'
    os.makedirs("/tmp/paper", exist_ok=True)
    t0 = int(round(time.time() * 1000))
    tmp_path = '/tmp/paper/%d.docx' % t0
    os.system('cp %s %s' % (answer_path, tmp_path))
    document = Document(tmp_path)
    # 设置整个文档的默认字体
    microsoft_font = u'宋体'  # u 表示后面的字符串以 Unicode 格式进行编码
    black_font = u'黑体'
    number_font = 'Times New Roman'
    area = qn('w:eastAsia')
    document.styles['Normal'].font.name = microsoft_font
    document.styles['Normal'].font.size = Pt(10.5)
    document.styles['Normal'].font.color.rgb = RGBColor(0, 0, 0)
    document.styles['Normal']._element.rPr.rFonts.set(area, number_font)
    # 指定段落样式
    styles = document.styles
    # fls = time.time()
    # strr = 'lbj_Style%s' %fls  #自定义的样式的名称
    # strr = strr.replace('.', '')
    # strr = strr + ''.join(random.sample('zyxwvutsrqponmlkjihgfedcbaABCDEFGHIJKLMNOPQRST', 5))
    s = styles.add_style('lbj_Style', WD_STYLE_TYPE.PARAGRAPH)
    s.font.name = microsoft_font
    s.font.size = Pt(10.5)
    s.font.color.rgb = RGBColor(0, 0, 0)
    s.paragraph_format.line_spacing = Pt(0)  # 行距值
    s.paragraph_format.space_before = Pt(0)  # 段前距
    s.paragraph_format.space_after = Pt(0)  # 段后距
    s.paragraph_format.line_spacing_rule = WD_LINE_SPACING.SINGLE  # 行间距
    s._element.rPr.rFonts.set(area, number_font)  # 除中文外其它文字 使用的字体 ,备选项

    paper_num_count_flag = 0  # 页面是否有页码条形码
    run = document.paragraphs[0]
    run.style = s
    p = run.add_run(main_title)
    font = p.font
    font.name = black_font
    font.color.rgb = RGBColor(0, 0, 0)
    font.size = Pt(15)
    run.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p = document.add_paragraph()
    p.add_run().add_picture(r'nile/static/mark_pic/prefix_2.png')

    p = document.add_paragraph()
    # p.add_run().add_break()
    run = p.add_run('选择题(请用2B铅笔填涂)')
    run.bold = True
    run.font.size = Pt(12)
    run.font.name = black_font
    # sub_mark_num_vec = []  # 每页竖长条表示块数量
    sub_mark_num = 0  # 竖长条表示块总数量
    sub_mark_choice = []  # 选择题黑块区域
    sub_mark_fillin = []  # 填空题黑块区域
    sub_mark_eassy = []  # 简答题黑块区域
    qus_range_choice = []  # 选择题题号范围
    qus_range_fillin = []  # 填空题题号范围
    qus_range_eassy = []  # 简答题题号范围
    paper_num = 0  # 页数
    ques_no = 0  # 题号
    choice_answer_cnt = []  # 选项列数
    choice_line_number = []  # 每行的题目数量
    choice_answer_pattern = []  # 每列选择题数目
    choice_col_num = []  # 选择题每行的列数
    option_len = []
    choice_ques_no, mm, combine_ques_index = [], [], []
    # break_page_ques_no = []  # 如果选择题分页时的题号
    count_ques = 0
    for key, value in sheet.items():
        if key == 'choice_question_all':
            for k in range(len(value)):
                q_no = value[k].get("q_no")
                opt_len = len(value[k].get("options"))
                mm.append(q_no)
                if not isinstance(q_no, list):
                    option_len.append(opt_len)
                else:
                    for qq in q_no:
                        option_len.append(opt_len)
    for i in range(len(mm)):
        if isinstance(mm[i], list):
            count_ques += len(mm[i])
            combine_ques_index.append(i)
            for j in mm[i]:
                choice_ques_no.append(j)
        else:
            count_ques += 1
            choice_ques_no.append(mm[i])
    # 选项个数不一样
    group_choice_count = {}
    group_choice_opt = {}  # 各选项数对应的选项数集合
    group_choice_num = {}  # 各选项数对应的题号集合
    for opt_i in range(len(option_len)):
        pre = option_len[opt_i]
        if not group_choice_count.get(pre):
            group_choice_count[pre] = 0
            group_choice_num[pre] = []
            group_choice_opt[pre] = []
        count = group_choice_count[pre]
        group_choice_count[pre] = count + 1
        group_choice_num[pre].append(choice_ques_no[opt_i])
        group_choice_opt[pre].append(option_len[opt_i])
    choice_group = sheet.get('choice_question', [])
    choice_len = len(choice_group)
    choice_len_sum = len(choice_ques_no)  # 选择题总数,包括组合题中的小选择题
    fillin_group = sheet.get('fillin_question', [])
    fillin_len = len(fillin_group)
    fs_num = fillin_group[0].get('q_no') if fillin_group else 0  # 填空题开始的题号
    subjective_question = sheet.get('subjective_question', [])
    subjec_len = len(subjective_question)
    ss_num = subjective_question[0].get('q_no') if subjective_question else 0  # 主观题开始的题号
    combine_question = sheet.get('combine_question', [])

    pic_in_sub = [[] for x in range(subjec_len)]
    pic_num = 0
    for ques in subjective_question:
        pic_in_card = ques.get('pic_in_card', "")
        pic_in_sub[pic_num] = pic_in_card if pic_in_card else []
        pic_num += 1
    tmp = []
    for i in range(len(mm)):
        if isinstance(mm[i], list):
            if tmp:
                qus_range_choice.append(tmp)
                tmp = []
            qus_range_choice.append(mm[i])
        else:
            tmp.append(mm[i])

    if not combine_question:
        qus_range_choice.append(tmp)
    else:
        if not isinstance(mm[-1], list):
            qus_range_choice.append(tmp)

    if fillin_group:
        qus_range_fillin.append(fs_num)
        qus_range_fillin.append(fs_num + fillin_len - 1)
    if subjective_question:
        qus_range_eassy.append(ss_num)
        qus_range_eassy.append(ss_num + subjec_len - 1)

    # row_n, row_rest = divmod(choice_len_sum, 15)
    # choice_row_num = row_n + 1 if row_rest else row_n  # 选择题行数
    # choice_row_num = [choice_row_num] if choice_row_num <= 4 else [4, choice_row_num-4]
    choice_row_num = 0
    rest = 0
    break_num = 0
    ap_n = 0  # choice_answer_pattern分页时的块数
    for key, value in group_choice_count.items():
        row_n, row_rest = divmod(value, 15)
        row_n5, row_rest5 = divmod(value, 5)
        for i in range(row_n):
            choice_line_number.append(5)
            choice_col_num.append(3)
        if row_rest:
            if row_rest > 10:
                choice_col_num.append(3)
            elif row_rest > 5:
                choice_line_number.append(5)
                choice_col_num.append(2)
            else:
                choice_line_number.append(row_rest)
                choice_col_num.append(1)
        for i in range(row_n5):
            choice_answer_pattern.append(5)
        if row_rest5:
            choice_answer_pattern.append(row_rest5)
        count_ed = row_n + 1 if row_rest else row_n
        choice_row_num += count_ed
        for i in range(count_ed):
            choice_answer_cnt.append(key)
        if choice_row_num == 4:
            rest = row_rest
        if choice_row_num > 4:
            if not break_num:
                if not rest:
                    break_num = group_choice_num[key][value - row_rest + 1]
                else:
                    break_num = group_choice_num[key][0]
    choice_row_num = [choice_row_num] if choice_row_num <= 4 else [4, choice_row_num - 4]
    choice_answer_cnt = [choice_answer_cnt] if not break_num else [choice_answer_cnt[:4], choice_answer_cnt[4:]]
    choice_col_num = [choice_col_num] if not break_num else [choice_col_num[:4], choice_col_num[4:]]
    choice_line_number = [choice_line_number] if not break_num else [choice_line_number[:4], choice_line_number[4:]]
    logger.info("group_choice_count========================={}".format(group_choice_count))
    logger.info("choice_answer_cnt========================={}".format(choice_answer_cnt))
    logger.info("choice_line_number========================={}".format(choice_line_number))

    group_choice_num_ = sorted(group_choice_num.items(), key=lambda d: d[0])
    group_choice_opt_ = sorted(group_choice_opt.items(), key=lambda d: d[0])
    group_choice_count_ = sorted(group_choice_count.items(), key=lambda d: d[0])
    # logger.info("group_choice_num_========================={}".format(group_choice_num_))
    choice_num = []
    for key, value in group_choice_num_:
        if isinstance(value, list):
            for i in value:
                choice_num.append(i)
        else:
            choice_num.append(value)
    choice_opt = []
    for key, value in group_choice_opt_:
        if isinstance(value, list):
            for i in value:
                choice_opt.append(i)
        else:
            choice_opt.append(value)

    row0 = choice_row_num[0]
    if break_num:
        for nn in choice_col_num[0:4]:
            ap_n += nn
        choice_answer_pattern = [choice_answer_pattern[0:ap_n], choice_answer_pattern[ap_n:]]
        row1 = choice_row_num[1]
        index = choice_ques_no.index(break_num)
        write_option(ques_no, choice_num[0:index], choice_opt[0:index], row0, document)
        document.add_page_break()
        write_option(ques_no, choice_num[index:], choice_opt[index:], row1, document)
    else:
        choice_answer_pattern = [choice_answer_pattern]
        write_option(ques_no, choice_num, choice_opt, row0, document)
    # write_option(ques_no, choice_len_sum, option_len, choice_ques_no, document)
    writeline(document, black_font)
    num, paper_num = choice0_60(fillin_len, fs_num, document, paper_num)
    paper_num += num

    if ss_num:
        sub_subjective(ss_num, paper_num, document, pic_in_sub)

    block_num = 0
    start = 0
    step = 3
    if choice_len_sum:
        for n in range(len(choice_row_num)):
            block_num += 1
            sub_mark_choice.append(start + step * (block_num - 1) - (block_num - 1))
            sub_mark_choice.append(start + step * block_num - (block_num - 1))
    if fillin_len:
        block_num += 1
        sub_mark_fillin.append(start + step * (block_num - 1) - (block_num - 1))
        sub_mark_fillin.append(start + step * block_num - (block_num - 1))
        if not subjec_len:
            index = sub_mark_fillin[-2]
            sub_mark_fillin.pop(-1)
            sub_mark_fillin.append(index + 1)
        else:
            for n in range(subjec_len):
                block_num += 1
                sub_mark_eassy.append(start + step * (block_num - 1) - (block_num - 1))
                sub_mark_eassy.append(start + step * block_num - (block_num - 1))
            if subjec_len == 1:
                index = sub_mark_eassy[-2]
                sub_mark_eassy.pop(-1)
                sub_mark_eassy.append(index + 1)
    else:
        if subjec_len:
            for n in range(subjec_len):
                block_num += 1
                sub_mark_eassy.append(start + step * (block_num - 1) - (block_num - 1))
                sub_mark_eassy.append(start + step * block_num - (block_num - 1))
            if subjec_len == 1:
                index = sub_mark_eassy[-2]
                sub_mark_eassy.pop(-1)
                sub_mark_eassy.append(index + 1)
        else:
            if sub_mark_choice:
                index = sub_mark_choice[-2]
                sub_mark_choice.pop(-1)
                sub_mark_choice.append(index + 1)

    #  return sub_mark_num
    for i in range(len(choice_row_num)):
        sub_mark_num += 2
    if fillin_len:
        sub_mark_num += 2
    for num in range(subjec_len):
        sub_mark_num += 2

    t1 = int(round(time.time() * 1000))
    doc_file_name = "{}-答题卡".format(sheet_name or str(t1))
    return_path = '/tmp/paper/%s.%s' % (doc_file_name, 'docx')
    document.save(return_path)
    sub_json_data = {}
    tmp_sub_mark_choice = []
    for i in range(len(choice_row_num)):
        tmp_sub_mark_choice.append([sub_mark_choice[i * 2], sub_mark_choice[i * 2 + 1]])
    logger.info("sub_mark_choice========================={}".format(sub_mark_choice))
    sub_json_data['sub_mark_choice'] = tmp_sub_mark_choice
    sub_json_data['sub_mark_fillin'] = sub_mark_fillin
    sub_json_data['sub_mark_eassy'] = sub_mark_eassy
    sub_json_data['sub_mark_num'] = sub_mark_num
    # sub_json_data['sub_mark_num_vec'] = sub_mark_num_vec
    sub_json_data['page_num'] = paper_num
    # sub_json_data['paper_num_count_flag'] = paper_num_count_flag
    sub_json_data['choice_answer_cnt'] = choice_answer_cnt
    sub_json_data['choice_line_number'] = choice_line_number
    sub_json_data['choice_answer_pattern'] = choice_answer_pattern
    sub_json_data['choice_col_num'] = choice_col_num
    sub_json_data['choice_row_num'] = choice_row_num
    sub_json_data['qus_range_choice'] = qus_range_choice
    sub_json_data['qus_range_fillin'] = qus_range_fillin
    sub_json_data['qus_range_eassy'] = qus_range_eassy
    logger.info("sub_json_data========================={}".format(sub_json_data))
    json_json = get_json(sub_json_data)
    logger.info("json_json========================={}".format(json_json))
    return return_path, sub_json_data
p = report_doc.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

report_doc.add_heading('Heading, level 1', level=1)
report_doc.add_paragraph('Intense quote', style='Intense Quote')
report_doc.add_paragraph('first item in unordered list', style='List Bullet')
report_doc.add_paragraph('first item in ordered list', style='List Number')
report_doc.add_picture('lombplot.png', width=Cm(14.8), height=Cm(5.86))

records = ((3, '101', '1号'), (7, '422', '二号'), (4, '631',
                                                'Spam, spam, eggs, and spam'))
table = report_doc.add_table(rows=1, cols=3, style="Light Shading Accent 1")
hdr_cells = table.rows[0].cells
hdr_cells[0].text = '正'
hdr_cells[1].text = '价'
hdr_cells[2].text = '它'
for qty, id, desc in records:
    row_cells = table.add_row().cells
    row_cells[0].text = str(qty)
    row_cells[1].text = id
    row_cells[2].text = desc
report_doc.add_page_break()
wkdir = os.curdir
file_name = os.path.join(wkdir, "testDemo.docx")
if os.path.exists(file_name):
    print(file_name, "has been removed.")
    os.remove(file_name)
report_doc.save(file_name)
docx2pdf.word2pdf("./testDemo.docx")
예제 #44
0
    def create_word(self, data):

        # 打开文档

        title=data['title']
        categorys=data['files']
        volumns=data['volumn']


        document = Document()
        # 加入不同等级的标题
        document.add_heading(title, 0)
        for cat in categorys:
            document.add_heading(cat['name'])
            file_path = os.path.join(sys.path[0], cat['filename'])
            document.add_picture(file_path, width=Inches(7.5))

        # document.add_heading(u'一级标题', 1)
        # document.add_heading(u'二级标题', 2)
        # 添加文本
        paragraph = document.add_paragraph(u'我们在做文本测试!')
        # 设置字号
        run = paragraph.add_run(u'设置字号、')
        run.font.size = Pt(24)

        # 设置字体
        run = paragraph.add_run('Set Font,')
        run.font.name = 'Consolas'

        # 设置中文字体
        run = paragraph.add_run(u'设置中文字体、')
        run.font.name = u'宋体'
        r = run._element
        r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')

        # 设置斜体
        run = paragraph.add_run(u'斜体、')
        run.italic = True

        # 设置粗体
        run = paragraph.add_run(u'粗体').bold = True

        # 增加引用
        document.add_paragraph('Intense quote', style='Intense Quote')

        # 增加无序列表
        document.add_paragraph(
            u'无序列表元素1', style='List Bullet'
        )
        document.add_paragraph(
            u'无序列表元素2', style='List Bullet'
        )
        # 增加有序列表
        document.add_paragraph(
            u'有序列表元素1', style='List Number'
        )
        document.add_paragraph(
            u'有序列表元素2', style='List Number'
        )
        # 增加图像(此处用到图像image.bmp,请自行添加脚本所在目录中)
        #filename = u'2018-001-2018年度1至4月-0.png'
        # filename = u'%s-%s-%s.png' % (self.code, self.name, i)

        # 增加表格
        table = document.add_table(rows=1, cols=3)
        hdr_cells = table.rows[0].cells
        hdr_cells[0].text = 'Name'
        hdr_cells[1].text = 'Id'
        hdr_cells[2].text = 'Desc'
        # 再增加3行表格元素
        for i in xrange(3):
            row_cells = table.add_row().cells
            row_cells[0].text = 'test' + str(i)
            row_cells[1].text = str(i)
            row_cells[2].text = 'desc' + str(i)

        # 增加分页
        document.add_page_break()

        # 保存文件
        document.save(u'测试.docx')

        filename = u'测试.docx'
        # filename = u'%s-%s-%s.png' % (self.code, self.name, i)
        file_path = os.path.join(sys.path[0], filename)

        with open(file_path, 'rb') as fp:
            data = fp.read().encode('base64')


        return data
예제 #45
0
    def process(self, full_list):
        excluded = self._excluded_loader.get_excluded()  #excluded IDs
        ipaddr = self._ipaddr
        #list of elements defined in find_items() which priority is greater than 'None'
        result_list = [
            x for x in full_list if x[1] not in excluded and x[0] < 4
        ]

        #DOCUMENT TEMPLATE
        #it has header and footer
        path = 'document.docx'
        document = Document(path)
        for i in range(len(result_list)):
            self._create_main_paragraph(document, i, result_list[i][1])

            table = document.add_table(cols=2, rows=2)
            table.alignment = WD_TABLE_ALIGNMENT.RIGHT
            for row in table.rows:
                for cell in row.cells:
                    cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
            table.columns[0].width = Cm(7.0)
            table.columns[1].width = Cm(9.0)
            for row in table.rows:
                row.height = Cm(0.8)

            run = table.cell(0, 0).paragraphs[0].add_run('Rick Score:')
            run.bold = True
            run.font.size = Pt(12)
            table.cell(0, 1).paragraphs[0].add_run(result_list[i][2])
            self._coloring_cells(table.cell(0, 1), table.cell(0, 1).text)

            run10 = table.cell(1, 0).paragraphs[0].add_run('Affected Systems:')
            table.cell(1, 1).paragraphs[0].add_run('https://' + ipaddr)
            run10.bold = True
            run10.font.size = Pt(12)

            if result_list[i][3] != None:
                table.add_row()
                run = table.cell(2,
                                 0).paragraphs[0].add_run('CVSS Risk Score:')
                table.cell(2, 1).paragraphs[0].add_run(result_list[i][3])
                run.bold = True
                run.font.size = Pt(12)
                table.rows[2].height = Cm(0.8)
                table.rows[2].cells[
                    0].vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
                table.rows[2].cells[
                    1].vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
            document.add_paragraph()

            self._create_content_paragraph(document, i, result_list[i][4], 1,
                                           'Vulnerability Description')

            #TBA evidence generation function
            self._create_content_paragraph(document, i, '<TBA>', 2, 'Evidence')

            self._create_content_paragraph(document, i, result_list[i][5], 3,
                                           'Recommendation')

            if result_list[i][7] != None:
                self._create_content_paragraph(document, i, result_list[i][6],
                                               4, 'References')
            document.add_page_break()

        self._create_main_paragraph(document, None, '2.      APPENDIX')
        document.add_paragraph()
        paragraph21 = document.add_paragraph()
        run = paragraph21.add_run('2.1.    Port Scan Results')
        run.bold = True
        run.font.size = Pt(14)
        document.add_paragraph()
        table = document.add_table(rows=1, cols=2)
        table.columns[0].width = Cm(8.0)
        table.alignment = WD_TABLE_ALIGNMENT.RIGHT
        table.cell(0, 0).text = ipaddr
        #TBA open ports find function
        table.cell(0, 1).text = '<TBA>'
        table.rows[0].height = Cm(0.9)
        for row in table.rows:
            for cell in row.cells:
                cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.TOP

        document.save('Nessus-result.docx')
def llenar_inter_regional(nombre_archivo):
    general = pd.read_csv("./archivos/current_general.csv",
                          sep=";",
                          encoding="latin")
    igm = str(general.iloc[0]["igm"])
    if igm == nan: igm = "IGM"
    archivo = Document(nombre_archivo)
    archivo.add_paragraph()
    archivo.add_heading("DESCRIPCIÓN MICROSCÓPICA")
    archivo.add_paragraph()
    subs = ["Textura general:", "Otras texturas:", "Observaciones:"]
    for i in subs:
        p1 = archivo.add_paragraph()
        r1 = p1.add_run(i)
        r1.bold = True
        r1.underline = True
        p1.add_run(" ")
        archivo.add_paragraph()

    archivo.add_page_break()
    archivo.add_paragraph()
    archivo.add_heading("COMPOSICIÓN MINERALÓGICA (%Vol) - " + igm)
    archivo.add_paragraph()
    rows = 12
    tabla_perc = archivo.add_table(rows, 6)
    for i in range(rows):
        for j in range(6):
            if j % 2 != 0:
                tabla_perc.cell(i, j).width = Cm(1)
            else:
                tabla_perc.cell(i, j).width = Cm(4)
    for i in range(6):
        if i % 2 != 0:
            colum = tabla_perc.columns[i]
            colum.width = Cm(1)
    tabla_perc.style = 'TableGrid'
    cells = [0, 1, 2, 3, 4, 4, 0, 2]
    content = [
        "MINERALES \nPRINCIPALES", "%", "MINERALES \nACCESORIOS", "%",
        "MINERALES DE ALTERACIÓN", "MINERALES DE INTRODUCCIÓN", "TOTAL",
        "TOTAL"
    ]

    for i in range(len(cells)):
        if i > 5:
            para = tabla_perc.cell(11, cells[i]).paragraphs[0]
        elif i == 5:
            para = tabla_perc.cell(6, cells[i]).paragraphs[0]
        else:
            para = tabla_perc.cell(0, cells[i]).paragraphs[0]
        r1 = para.add_run(content[i])
        r1.bold = True

    tabla_perc.cell(0, 4).merge(tabla_perc.cell(0, 5))
    tabla_perc.cell(6, 4).merge(tabla_perc.cell(6, 5))
    archivo.add_paragraph()
    caracteristicas = [
        "PARAGÉNESIS:", "TIPO DE METAMORFÍSMO:", "FACIES DE METAMORFISMO:",
        "PROTOLITO:"
    ]
    for i in caracteristicas:
        p1 = archivo.add_paragraph()
        r1 = p1.add_run(i)
        r1.bold = True
        r1.underline = True
        p1.add_run(" ")
    clas_roc = archivo.add_paragraph()
    run = clas_roc.add_run("CLASIFICACIÓN DE LA ROCA ")
    run.bold = True
    run.underline = True
    r2 = clas_roc.add_run("(Basada en SSMR, 2007):")
    r2.underline = True
    clas_roc.add_run(" La clasificación")
    archivo.add_paragraph()
    archivo.add_heading("DESCRIPCIÓN MICROSCÓPICA DE MINERALES")
    archivo.add_paragraph()
    p1 = archivo.add_paragraph()
    r1 = p1.add_run("Mineral 1:")
    r1.bold = True
    r1.underline = True
    p1.add_run(
        " Descripción concisa y completa de rasgos generales y particulares, "
        +
        "sin olvidar tamaño, forma, color, distribución, relaciones texturales, "
        + "extinción, clivaje, etc")
    archivo.add_paragraph()
    archivo.save(nombre_archivo)
예제 #47
0
def draft_ta(request,id):

    doc_final_path ='E:/certa-drdo/certa/Draft_TA.docx' 
    pdf_final_path ='E:/certa-drdo/certa/Draft_TA.pdf' 
    final_path='E:/certa-drdo/certa/'
    if os.path.isfile(pdf_final_path):
        with open(pdf_final_path, 'rb') as pdf:
            response = HttpResponse(pdf.read(),content_type='application/pdf')
            response['Content-Disposition'] = 'filename=some_file.pdf'
        return response
    elif os.path.isfile(doc_final_path):
        print('mmmmmmmmmmmmmm')
        pythoncom.CoInitialize()
        wdFormatPDF = 17
        # print(tempfile.gettempdir(),'temp')

        in_file = os.path.abspath(doc_final_path)
        # out_file = os.path.abspath('D:/cemilac/certa/defence/media/org1.pdf')

        word = comtypes.client.CreateObject('Word.Application')
        doc = word.Documents.Open(in_file)
        doc.SaveAs('E:/certa-drdo/certa/Draft_TA.pdf', FileFormat=wdFormatPDF)
        print('nnnnnnnnnnn')
        doc.Close()
        word.Quit()
        with open(final_path+'Draft_TA.pdf', 'rb') as pdf:
            response = HttpResponse(pdf.read(),content_type='application/pdf')
            response['Content-Disposition'] = 'filename=some_file.pdf'
        return response
    else:
    
        idprefix=request.POST['idprefix']
        print(idprefix,'jjjjjjjjjjjj')

        curr_path = "/"+str(id)+ "/"+idprefix+"Annexure 7/"
        curr_path=curr_path.replace('/','\\')
        new_path = os.path.join(settings.MEDIA_ROOT + curr_path)
    
        # if os.path.isdir(new_path):
        #     with open(new_path+'Draft_TA.pdf', 'rb') as pdf:
        #         response = HttpResponse(pdf.read(),content_type='application/pdf')
        #         response['Content-Disposition'] = 'filename=some_file.pdf'
        #     return response
        # else:
        taa=TAapplicationmodel.objects.filter(user_id=id).first()

        # template = get_template('dealing officer/Draft TA pdf.html')
        target_file = StringIO()
        template = DocxTemplate("E:/certa-drdo/certa/dashboard/templates/dealing officer/template.docx")
        context= {
            'firmname':taa.firmname,
            'addr1':taa.addr1,
            'item_name':taa.item_name,
            'part_no':taa.part_no

        }
        html = template.render(context)
        doc_io = io.BytesIO() # create a file-like object
        template.save("Draft_TA.docx") # save data to file-like object

        
        new_path1 = 'E:\certa-drdo\certa\Draft_TA.docx'
        output_path = os.path.join(settings.MEDIA_ROOT) + '/89/result.pdf'
        # new_path=new_path.replace('\','//')

        taa=TAapplicationfiles.objects.filter(user_id=id,refid=idprefix,refpath='Annexure 4.13').first()
        aesurl=taa.filepath
        docurl = aesurl[:-4]
        print('aesview',aesurl)
        print('docurl',docurl)

        bufferSize = 64 * 1024
        passw = "#EX\xc8\xd5\xbfI{\xa2$\x05(\xd5\x18\xbf\xc0\x85)\x10nc\x94\x02)j\xdf\xcb\xc4\x94\x9d(\x9e"
        encFileSize = stat(aesurl).st_size
        with open(aesurl, "rb") as fIn:
            with open(docurl, "wb") as fOut:
                pyAesCrypt.decryptStream(fIn, fOut, passw, bufferSize, encFileSize)

        # curr_path = "/"+str(id)+ "/Annexure 4.13/PC/pc.docx.aes"
        # curr_path=curr_path.replace('/','\\')
        
        # new_path = os.path.join(settings.MEDIA_ROOT + curr_path)
        # templateDoc = Document(new_path1)
        templateDoc1 = Document(new_path1)
        templateDoc = Document(docurl)

        templateDoc1.add_page_break()
        
        for element in templateDoc.element.body:
            templateDoc1.element.body.append(element)

        templateDoc1.save(new_path1)
        print(request.user.id,'kkkkkkkk')
        messages.success(request, 'Draft_TA Successfully Prepared, Click again to view the file !')
        reg=TAapplicationmodel.objects.filter(file_in_id=str(request.user.id),file_in_name="TCS-DO")
        print('reggggggg',reg)
        return render(request, 'tcs do/receivedtyperecord.html',{'details':reg,'status':True})
예제 #48
0
# 添加一个段落
paragraph = document.add_paragraph('Lorem ipsum dolor sit amet.')
# 在paragraph之前添加一个prior_paragraph的段落
prior_paragraph = paragraph.insert_paragraph_before('Lorem ipsum')
# 段落之后添加内容
paragraph = document.add_paragraph('Lorem ipsum ')
paragraph.add_run('dolor sit amet.')

# 添加一个标题
document.add_heading('The REAL meaning of the universe')
# 可以选择level 1 to 9 的标题
document.add_heading('The role of dolphins', level=2)

# 添加分页
document.add_page_break()

# 添加表格
table = document.add_table(rows=2, cols=2)
# 访问单元格 0 和 1 表示行 & 列
cell = table.cell(0, 1)
# 单元格添加文本
cell.text = 'parrot, possibly dead'
# 访问一行中的某列单元格
row = table.rows[1]
row.cells[0].text = 'Foo bar to you.'
row.cells[1].text = 'And a hearty foo bar to you too sir!'
# 添加一行
row = table.add_row()

# 单元格迭代
예제 #49
0
def generate_word(problems, problem_list, is_answer_sheet=False):
    buffer_word = BytesIO()
    document = Document()
    document.styles['Normal'].font.name = 'Times New Roman'
    document.styles['Normal'].element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
    word_content = []
    # Unpack problem list
    index = 0
    for chapter in problem_list:
        for chapter_id in chapter:
            for problem_type in chapter[chapter_id]:
                for problem_id in chapter[chapter_id][problem_type]:
                    index += 1
                    content = problems[problem_type][problem_id]
                    # Shared parts - Header and Body
                    if problem_type == 'cp' and index > 1:
                        word_content.append(None)
                    word_content.append([
                        f'第{index}题 {content["type_sc"]}({content["points"]}分)',
                        'bold'
                    ])
                    word_content.extend(content['desc_lines'])
                    if 'image' in content:
                        word_content.append([content['image'], 'image'])
                    if problem_type == 'cp':
                        word_content.append('')
                        for sub in content['sub']:
                            sub_points = round(content['points'] *
                                               sub['percentage'] / 100)
                            word_content.append([
                                f'第{sub["order"]}小题 {sub["type_sc"]}({sub_points}分)',
                                'bold'
                            ])
                            word_content.extend(sub['desc_lines'])
                            if 'image' in sub:
                                word_content.append([sub['image'], 'image'])
                            # Body cont'd
                            if 'choice_lines' in sub:
                                for i in range(len(sub['choice_lines'])):
                                    word_content.append(sub['choice_lines'][i])
                                    if chr(65 + i) in sub:
                                        word_content.append(
                                            [sub[chr(65 + i)], 'image'])
                            # Footer
                            ans_lines = '\n'.join(sub['ans_lines'])
                            word_content.append(
                                f'答案:{ans_lines if is_answer_sheet else "___________"}'
                            )
                            if is_answer_sheet and 'answer_image' in sub:
                                word_content.append(
                                    [sub['answer_image'], 'image'])
                            word_content.append('')
                        word_content.append(None)
                    else:
                        # Body cont'd
                        if 'choice_lines' in content:
                            for i in range(len(content['choice_lines'])):
                                word_content.append(content['choice_lines'][i])
                                if chr(65 + i) in content:
                                    word_content.append(
                                        [content[chr(65 + i)], 'image'])
                        # Footer
                        ans_lines = '\n'.join(content['ans_lines'])
                        if 'error' in content:
                            ans_lines += f'(±{content["error"]}%)'
                        word_content.append(
                            f'答案:{ans_lines if is_answer_sheet else "___________"}'
                        )
                        if is_answer_sheet and 'answer_image' in content:
                            word_content.append(
                                [content['answer_image'], 'image'])
                        word_content.append('')
    word_content = word_content if word_content[
        -1] is not None else word_content[:-1]
    on_content = False
    for paragraph in word_content:
        if paragraph is None:
            if on_content:
                on_content = False
                document.add_page_break()
        elif isinstance(paragraph, list):
            on_content = True
            if paragraph[1] == 'bold':
                p = document.add_paragraph()
                p.add_run(paragraph[0]).bold = True
                p.style = document.styles['Normal']
            elif paragraph[1] == 'image':
                p = document.add_paragraph()
                run = p.add_run()
                inline_shape = run.add_picture(paragraph[0])
                if inline_shape.width > Inches(5):
                    inline_shape.height = Inches(5 * inline_shape.height /
                                                 inline_shape.width)
                    inline_shape.width = Inches(5)
        else:
            on_content = True
            p = document.add_paragraph(paragraph)
            p.style = document.styles['Normal']
    document.save(buffer_word)
    buffer_value = buffer_word.getvalue()
    buffer_word.close()
    return buffer_value
예제 #50
0
파일: docx.py 프로젝트: euphoris/firstaid
class DOCX():
    def __init__(self):
        self.doc = Document()
        # page dimensions
        self.PAGE_WIDTH = self.doc.sections[0].page_width.pt
        self.PAGE_HEIGHT = self.doc.sections[0].page_height.pt
        # margins
        self.PAGE_LEFT_MARGIN = self.doc.sections[0].left_margin.pt
        self.PAGE_RIGHT_MARGIN = self.doc.sections[0].right_margin.pt
        self.PAGE_TOP_MARGIN = self.doc.sections[0].top_margin.pt
        self.PAGE_BOTTOM_MARGIN = self.doc.sections[0].bottom_margin.pt
        self.PAGE_HEADER_DISTANCE = self.doc.sections[0].header_distance.pt
        self.PAGE_FOOTER_DISTANCE = self.doc.sections[0].footer_distance.pt
        # dimensions including margins
        self.ACTUAL_PAGE_WIDTH = self.PAGE_WIDTH - self.PAGE_LEFT_MARGIN - self.PAGE_RIGHT_MARGIN
        self.ACTUAL_PAGE_HEIGHT = self.PAGE_HEIGHT - self.PAGE_TOP_MARGIN - self.PAGE_BOTTOM_MARGIN - \
                                  self.PAGE_HEADER_DISTANCE - self.PAGE_FOOTER_DISTANCE
        # style
        self.TABLE_STYLE = 'LightShading-Accent1'
        self.FIRST_LINE_INDENT = Cm(1)

    def add_paragraph(self, content):
        """
        add paragraphs to page
        :param content: list of strings. ex) ['first paragraph', 'second paragraph']
        """
        for con in content:
            paragraph = self.doc.add_paragraph(con)
            if len(con) > 45:
                paragraph.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
            paragraph.paragraph_format.first_line_indent = self.FIRST_LINE_INDENT

    def add_title(self, content):
        """
        add heading to page
        :param content: string. ex) 'Heading 1'
        """
        self.doc.add_heading(content)

    def add_image(self, filename):
        """
        add image to page
        :param filename: file name
        """
        im = Image.open(filename)
        sd = {
            'width': self.ACTUAL_PAGE_WIDTH,
            'height': self.ACTUAL_PAGE_HEIGHT
        }
        d = {'width': im.width, 'height': im.height}

        max_key = max(d.keys(), key=lambda k: d[k])
        all_keys = list(d.keys())
        all_keys.pop(all_keys.index(max_key))
        counterpart = all_keys[0]

        if d[max_key] > sd[max_key]:  # larger than suggested
            new_max_value = sd[max_key]
        else:  # smaller than suggested
            new_max_value = d[max_key]

        d['new_{}'.format(
            counterpart)] = new_max_value * d[counterpart] / d[max_key]
        d['new_{}'.format(max_key)] = new_max_value

        fig = BytesIO()
        im.save(fig, 'PNG')
        fig.seek(0)
        self.doc.add_picture(fig, Pt(d['new_width']), Pt(d['new_height']))
        last_paragraph = self.doc.paragraphs[-1]
        last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER  # align image to center of page

    def add_table(self, df):
        """
        add table to slide
        :param df: pandas DataFrame
        """
        table = self.doc.add_table(df.shape[0] + 1, df.shape[1] + 1)
        table.style = self.TABLE_STYLE
        # column title
        for i, col in enumerate(df.columns):
            table.cell(0, i + 1).text = str(col)
        # row title
        for i, row in enumerate(df.index):
            table.cell(i + 1, 0).text = str(row)
        # values
        for i, row in enumerate(df.index):
            for e, item in enumerate(df.loc[row]):
                table.cell(i + 1, e + 1).text = str(item)

        return table

    def page_break(self):
        """
        add page break
        """
        self.doc.add_page_break()

    def blank_line(self):
        """
        add new line
        """
        self.doc.add_paragraph('')

    def add(self, content='', image=''):
        """
        main function to add content to page
        :param content: content to insert in page
        :param image: only used if content is image files
        """
        # image
        if image:
            self.add_image(image)
        # string
        if isinstance(content, list):
            self.add_paragraph(content)
        # title
        elif isinstance(content, str):
            self.add_title(content)
        # table
        elif isinstance(content, pd.DataFrame):
            self.add_table(content)

    def save(self, file_name):
        """
        save document
        :param file_name: file name. ex) 'test.docx'
        """
        self.doc.save(file_name)
예제 #51
0
class Renderer(abstractRenderer.AbstractRenderer):
    
    def __init__(self, inputDir, outputDir, outputName, config):
        abstractRenderer.AbstractRenderer.__init__(self, inputDir, outputDir, outputName, config)
        self.document = Document()
        self.currentParagraph = self.document.add_paragraph()
        self.outputFilename = os.path.join(outputDir, outputName + '.docx')
        self.inputDir = inputDir
        self.f = codecs.open('/dev/null', 'w', 'utf_8_sig')
        self.currentChapter = ''
        self.currentBook = ''
        self.in_nd = False
        self.in_footnote = False
        # Old:
        # Flags
        self.printerState = {'li': False, 'd': False, 'm': False}
        self.smallCapSections = True  # Sometimes we don't want to do this, like for Psalms
        self.justDidLORD = False
        self.justDidNB = False
        self.doNB = False
        self.narrower = False
        self.doChapterOrVerse = ''
        self.smallcaps = False

    def render(self, order='normal'):
        self.loadUSFM(self.inputDir)
        self.run(order)
        self.document.save(self.outputFilename)        
    
    #
    #   Support
    #

    def startNarrower(self, n):
        s = '}' if self.narrower else '\n\\blank[medium] '
        self.narrower = True
        s = s + '\n\\noindentation \\Q{' + str(n) + '}{'
        self.doNB = True
        return s

    def stopNarrower(self):
        s = '}\n\\blank[medium] ' if self.narrower else ''
        self.narrower = False
        return s

    def escapeText(self, s):
        return s.replace('&', '\\&').replace('%', '\\%')
          
    def startLI(self):
        if self.printerState['li'] == False:
            self.printerState['li'] = True
            #return u'\startitemize \item '
            return r'\startexdent '
        else:
            #return u'\item '
            return r'\par '
        
    def stopLI(self):
        if self.printerState['li'] == False:
            return ''
        else:
            self.printerState['li'] = False
            #return u'\stopitemize'
            return r'\stopexdent '

    def startD(self):
        if self.printerState['d'] == False:
            self.printerState['d'] = True
        return '\par {\startalignment[middle] \em '

    def stopD(self):
        if self.printerState['d'] == False:
            return ''
        else:
            self.printerState['d'] = False
            return '\stopalignment }'
            
    def startM(self):
        r = self.stopD() + self.stopLI() + self.stopNarrower()
        self.printerState['m'] = True
        return r + r'\par {\startalignment[flushleft] '

    def stopM(self):
        if self.printerState['m'] == False:
            return ''
        else:
            self.printerState['m'] = False
            return '\stopalignment }'

    def newLine(self):
        s = '\n\par \n'
        if self.doNB:
            self.doNB = False
            self.justDidNB = True
            s = s + r'\noindentation '
        elif self.justDidNB:
            self.justDidNB = False
            s = s + r'\indentation '
        return s
                    
    #
    #   Used helpers for Docx
    #
    def clean(self, token):
        return token.getValue().replace('~', ' ')
        
    def newPara(self):
        self.currentParagraph = self.document.add_paragraph()

    #
    #   Tokens
    #

    def render_h(self, token):       self.document.add_page_break(); self.currentBook = token.getValue()
    def render_mt1(self, token):     self.document.add_heading(self.clean(token), level=0)
    def render_mt2(self, token):     self.document.add_heading(self.clean(token), level=1)
    def render_ms1(self, token):     self.document.add_heading(self.clean(token), level=2)
    def render_ms2(self, token):     self.document.add_heading(self.clean(token), level=3)
    def render_p(self, token):       self.newPara(); 
    def render_pi(self, token):      self.newPara(); self.currentParagraph.left_indent = Inches(1)

    def render_s1(self, token):      self.document.add_heading(self.clean(token), level=4)
    def render_s2(self, token):      self.document.add_heading(self.clean(token), level=5)

    def render_c(self, token):        self.currentChapter = token.getValue()
    def render_v(self, token):
        if token.getValue() == '1':
            run = self.currentParagraph.add_run(self.currentBook + ' ' + self.currentChapter + ' ')
            run.font.color.rgb = RGBColor(255, 0, 0)
        else:
            run = self.currentParagraph.add_run(token.getValue() + ' ')
            run.font.color.rgb = RGBColor(0, 140, 0)
        run.font.superscript = True
            
    def render_text(self, token):
        run = self.currentParagraph.add_run(self.clean(token) + ' ')
        if self.in_nd: 
            run.font.small_caps = True
        elif self.in_footnote:
            run.font.color.rgb = RGBColor(0, 0, 140)
        else:
            pass
        
    def render_q1(self, token):     self.newPara(); self.currentParagraph.paragraph_format.space_after = Pt(0)
    def render_q2(self, token):     self.newPara(); self.currentParagraph.paragraph_format.space_after = Pt(0); self.currentParagraph.add_run('\t')
    def render_q3(self, token):     self.newPara(); self.currentParagraph.paragraph_format.space_after = Pt(0); self.currentParagraph.add_run('\t\t')
    def render_nb(self, token):     self.newPara(); self.currentParagraph.left_indent = Inches(0)
    def render_b(self, token):      self.newPara(); self.currentParagraph.paragraph_format.space_after = Pt(0)

    def render_d(self, token):      self.newPara(); self.currentParagraph.paragraph_format.space_after = Pt(0)

    def render_f_s(self, token):
        run = self.currentParagraph.add_run(' [[ ')
        run.font.color.rgb = RGBColor(0, 0, 140)
        self.in_footnote = True
    def render_f_e(self, token):
        run = self.currentParagraph.add_run(' ]] ')
        run.font.color.rgb = RGBColor(0, 0, 140)
        self.in_footnote = False
    
    def render_nd_s(self, token): pass
    def render_nd_e(self, token):
        run = self.currentParagraph.runs[-1]
        run.font.small_caps = True

    def render_em_s(self, token): pass
    def render_em_e(self, token):
        run = self.currentParagraph.runs[-1]
        run.italic = True

    # SELAH
    def render_qs_s(self, token): pass
    def render_qs_e(self, token):
        run = self.currentParagraph.runs[-1]
        run.italic = True

    def render_wj_s(self, token): pass
    def render_wj_e(self, token):
        run = self.currentParagraph.runs[-1]
        run.font.color.rgb = RGBColor(140, 0, 0)
    
    def render_is1(self, token):    self.render_s1(token)
    def render_ip(self, token):     self.render_p(token)
    def render_iot(self, token):    self.render_q1(token)
    def render_io1(self, token):    self.render_q2(token)
    
    def render_pb(self, token):     self.document.add_page_break()
    def render_m(self, token):      self.render_p(token)
    
    #
    #   Introductory codes
    #
    
    introTeXt = str(r""" """)
    closeTeXt = r""" """
예제 #52
0
def generate_docx():
    # 创建文档对象
    document = Document()

    # 设置默认字体
    document.styles['Normal'].font.name = '微软雅黑'
    document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), '微软雅黑')

    # 创建自定义段落样式(第一个参数为样式名, 第二个参数为样式类型, 1为段落样式, 2为字符样式, 3为表格样式)
    UserStyle1 = document.styles.add_style('UserStyle1', 1)
    # 设置字体尺寸
    UserStyle1.font.size = Pt(40)
    # 设置字体颜色
    UserStyle1.font.color.rgb = RGBColor(0xff, 0xde, 0x00)
    # 居中文本
    UserStyle1.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    # 设置中文字体
    UserStyle1.font.name = '微软雅黑'
    UserStyle1._element.rPr.rFonts.set(qn('w:eastAsia'), '微软雅黑')

    # 创建自定义字符样式(第一个参数为样式名, 第二个参数为样式类型, 1为段落样式, 2为字符样式, 3为表格样式)
    UserStyle2 = document.styles.add_style('UserStyle2', 2)
    # 设置字体尺寸
    UserStyle2.font.size = Pt(15)
    # 设置字体颜色0c8ac5
    UserStyle2.font.color.rgb = RGBColor(0x0c, 0x8a, 0xc5)
    # 设置段落样式为宋体
    UserStyle2.font.name = '宋体'
    UserStyle2._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')

    # 使用自定义段落样式
    document.add_paragraph('自定义段落样式', style=UserStyle1)

    # 使用自定义字符样式
    document.add_paragraph('').add_run(
        '正月里采花无哟花采,二月间采花花哟正开,二月间采花花哟正开。三月里桃花红哟似海,四月间葡萄架哟上开,四月间葡萄架哟上开。',
        style=UserStyle2)

    # 设置粗体字
    document.add_paragraph('设置粗体字:').add_run('粗体字').bold = True

    # 设置斜体字
    document.add_paragraph('设置斜体字:').add_run('斜体字').italic = True

    # 设置字号50
    document.add_paragraph('设置字号50:').add_run('50').font.size = Pt(50)

    # 设置字体颜色为 af2626
    document.add_paragraph('设置字体颜色:').add_run('颜色').font.color.rgb = RGBColor(
        0xaf, 0x26, 0x26)

    # 样式叠加: 将字体改到30号并且将字体改成特定颜色;
    doubleStyle = document.add_paragraph('同时设置文字颜色和字号:').add_run('颜色和尺寸')
    doubleStyle.font.size = Pt(30)
    doubleStyle.font.color.rgb = RGBColor(0xaf, 0x26, 0x26)

    # 添加分页符
    document.add_page_break()

    # 创建 有序列表
    document.add_paragraph('').add_run('有序列表').font.size = Pt(30)
    document.add_paragraph('把冰箱门打开', style='List Number')
    document.add_paragraph('把大象装进去', style='List Number')
    document.add_paragraph('把冰箱门关上', style='List Number')

    # 创建 无序列表
    document.add_paragraph('').add_run('无序列表').font.size = Pt(30)
    document.add_paragraph('天地匆匆 惊鸿而过 路有千百个', style='List Bullet')
    document.add_paragraph('遑遑无归 闲云逸鹤 人间红尘过', style='List Bullet')
    document.add_paragraph('引势而流 鸿门乱局 各有各选择', style='List Bullet')
    document.add_paragraph('乾震坎艮 坤巽离兑 定一切生克', style='List Bullet')

    # 添加分页符
    document.add_page_break()
    # 添加图片
    document.add_paragraph('').add_run('添加图片').font.size = Pt(30)
    # document.add_picture('少女17087938.jpg', width=Inches(5))

    # 添加分页符
    document.add_page_break()

    document.add_paragraph('').add_run('创建表格').font.size = Pt(30)
    # 创建两行两列的表格
    rows_num = 5
    cols_num = 6
    table = document.add_table(rows=rows_num,
                               cols=cols_num,
                               style='Table Grid')

    for r in range(rows_num):
        for c in range(cols_num):
            table.cell(r, c).text = "第{r}行{c}列".format(r=r + 1, c=c + 1)
    # 保存文档
    document.save('Python生成的文档.docx')
예제 #53
0
    def save(self, fn, quizData, title='CMA Bible Quizzes', msg=None):
        """This method creates the quiz packet Word document.
        
         Args:
           fn (string): output filename of quiz
           quizData (dict): quizData object
           title (string): title in the document
           msg (string): optional message to write
        """

        #
        # document, paragraph, section, font settings
        #
        # -- width for columns: question number, type, Q/A, reference
        if (quizData['type'] == 'epistle'):
            width = [Inches(0.375), Inches(0.375), Inches(5.25), Inches(1.)]
        else:
            width = [Inches(0.375), Inches(1), Inches(4.625), Inches(1.)]

        document = Document()
        sections = document.sections
        section = sections[0]
        section.left_margin = Inches(0.75)
        section.top_margin = Inches(0.5)
        section.bottom_margin = Inches(0.5)
        section.right_margin = Inches(0.5)

        style = document.styles['Normal']
        font = style.font
        font.name = 'Arial'
        font.size = Pt(9)

        paragraph_format = document.styles['Normal'].paragraph_format
        paragraph_format.space_after = Pt(3)

        #
        # add the title
        #
        document.add_heading(title, 0)

        #
        # add the message
        #
        # if(msg==None):
        #     if(self.quizType!='custom'):
        #         msg={'intro':'This is a quiz packet for WGLD.  The quiz packet should have these characteristics:',
        #             'list':['Unique questions for each quiz (if possible) in the packet',
        #                     'Satisfaction of question minimums and maximums for each type',
        #                     '"A" division quizzes have 50% current and 50% past periods.',
        #                     '"B" division quizzes are only current content, and will therefore have repeats.'+\
        #                     '  We have tried to keep these in the alternative questions 16A, 16B, etc.  Replace as necessary.']}
        #     else:
        #         msg={'intro':'This is a custom quiz.'}

        # p = document.add_paragraph(msg['intro'])

        # #document.add_paragraph('Unique questions for each quiz (if possible) in the packet', style='List Bullet')
        # #document.add_paragraph(
        # #    'Satisfaction of question minimums and maximums for each type', style='List Bullet'
        # #)
        # if('list' in msg):
        #     for m in msg['list']:
        #         document.add_paragraph(m, style='List Bullet')

        # default message
        if (msg == None):
            msg=[{'type':'p','text':'This is a CM&A quiz packet.  The quiz packet should have these characteristics:'},
                 {'type':'list','text':['Unique questions for each quiz (if possible) in the packet',
                            'Satisfaction of question minimums and maximums for each type (2018 rules)',
                            '"A" division quizzes have 50% current and 50% past periods.',
                            '"B" division quizzes are only current content, and will therefore have repeats.'+\
                            '  We have tried to keep these in the alternative questions 16A, 16B, etc.  Replace as necessary.']}]

        for ii, m in enumerate(msg):
            if (m['type'] == 'p'):
                # normal paragraph
                p = document.add_paragraph(m['text'])
            elif (m['type'] == 'list'):
                # bulleted list
                for mitem in m['text']:
                    document.add_paragraph(mitem, style='List Bullet')

        #
        # loop through quizzes
        #
        for qi, QZ in enumerate(quizData['quizzes']):

            chapList = sorted(QZ['CH'].unique())
            logger.debug('chapters: %s' % str(chapList))

            if (qi > 0):
                document.add_page_break()
            document.add_heading('Quiz %d' % (qi + 1), 1)

            table = document.add_table(rows=1, cols=4)
            #table.style = 'LightShading-Accent1'
            table.style = 'LightGrid-Accent1'
            hdr_cells = table.rows[0].cells
            hdr_cells[0].text = '#'
            hdr_cells[1].text = 'Type'
            hdr_cells[2].text = 'Question'
            hdr_cells[3].text = 'Verse'
            for k, cell in enumerate(hdr_cells):
                cell.width = width[k]

            #
            # loop through questions
            #
            ii = 0
            for idx, row in QZ.iterrows():
                ii += 1
                row_cells = table.add_row().cells

                # Question Number
                row_cells[0].text = row.qn
                # Question Type
                row_cells[1].text = row.TYPE

                # https://stackoverflow.com/questions/36894424/creating-a-table-in-python-docx-and-bolding-text#36897305

                #
                # Question/Answer cell
                #
                c = row_cells[2]
                q = 'Q: %s' % row.QUESTION
                keywords = row.QKEYWORDS.split(',')

                self.boldText(cell=c, text=q, keywords=keywords)
                c.add_paragraph()

                #
                # ANSWER
                #
                a = 'A: %s' % row.ANSWER
                keywords = row.AKEYWORDS.split(',')
                self.boldText(cell=c, text=a, keywords=keywords)

                # book, chapter, verse, and club (e.g. 150,300)
                txt = '%s %s:%s' % (row.BK, row.CH, row.VS)
                if (isinstance(row.VE, float)):
                    txt += '-%s' % str(int(row.VE))

                txt += '\n('
                if (isinstance(row.CLUB, float)):
                    #txt+='\n(%d)'%row.CLUB
                    txt += '%d,' % row.CLUB
                if (row.SET is not None):
                    txt += '%s' % row.SET
                txt += ')'

                # additional flags (repeats)
                c = row_cells[3]
                if ('R' in row['FLAGS']):
                    txt += '\nrepeat'
                    c._tc.get_or_add_tcPr().append(
                        parse_xml(r'<w:shd {} w:fill="FFFF00"/>'.format(
                            nsdecls('w'))))
                c.text = txt

                # adjust width
                for k, cell in enumerate(row_cells):
                    cell.width = width[k]

            #
            # quiz stats
            #
            stats = quizData['stats'][qi]
            qdist = quizData['distribution']
            if (quizData['type'] != 'custom'):
                #
                # normal quiz
                #
                # -- min distribution
                msg = 'Regular quiz distribution (does not include overtime); '
                first = 1
                # loop through all the types to show minimums
                for qt, cnt in stats['min'].items():
                    msg += '%s:%d-%d (' % (qt.upper(), cnt, stats['max'][qt])
                    if (first):
                        first = 0
                        msg += 'req: '
                    msg += '%d-%d), ' % (qdist[qt]['range'][0],
                                         qdist[qt]['range'][1])
                msg = msg[:-2]  # get rid of trailing space and comma at end
                #
                # -- period stats
                #
                msg += '; Question counts by period (numbered): '
                for period, cnts in stats['period'].items():
                    msg += '%s=%d; ' % (period, cnts[0])
                msg = msg[:-2]
            else:
                # custom quiz
                msg = 'Custom quiz distribution; '
                #for qt,cnt in self._countTypes(QZ).items():
                for qt, cnt in countTypes(QZ, qdist).items():
                    msg += ' %s(%d),' % (qt, cnt)
                msg = msg[:-1]
                print(msg)
            #
            # add stats to document
            #
            document.add_paragraph(msg)

        #
        # extra question
        #
        if (quizData['type'] != 'custom'):
            document.add_page_break()
            document.add_heading('Extra Questions', level=1)

            msg = """This section contains extra questions of each type for use during the quiz day.
            Make sure to mark the questions used as you use them.
            """
            p = document.add_paragraph(msg)

            for qt, v in quizData['extraQuestions'].items():
                tlist = ', '.join(
                    [x.upper() for x in quizData['distribution'][qt]['types']])
                document.add_heading(
                    '%s Extra Questions (%s)' %
                    (quizData['distribution'][qt]['label'], tlist),
                    level=2)

                table = document.add_table(rows=1, cols=4)
                table.style = 'LightGrid-Accent1'
                hdr_cells = table.rows[0].cells
                hdr_cells[0].text = '#'
                hdr_cells[1].text = 'Type'
                hdr_cells[2].text = 'Question'
                hdr_cells[3].text = 'Verse'
                for k, cell in enumerate(hdr_cells):
                    cell.width = width[k]

                ii = 0
                for idx, row in quizData['extraQuestions'][qt].iterrows():
                    ii += 1
                    row_cells = table.add_row().cells
                    row_cells[0].text = str(ii)
                    row_cells[0].width = width[0]
                    row_cells[1].text = row.TYPE
                    #row_cells[2].text = 'Q: %s\n\nA: %s'%(row.QUESTION,row.ANSWER)

                    #
                    # QUESTION
                    #
                    c = row_cells[2]
                    q = 'Q: %s' % row.QUESTION
                    keywords = row.QKEYWORDS.split(',')
                    self.boldText(cell=c, text=q, keywords=keywords)

                    c.add_paragraph()
                    #c.add_paragraph()

                    #
                    # ANSWER
                    #
                    a = 'A: %s' % row.ANSWER
                    keywords = row.AKEYWORDS.split(',')
                    self.boldText(cell=c, text=a, keywords=keywords)

                    #
                    # VERSES
                    #
                    txt = '%s %s:%s' % (row.BK, row.CH, row.VS)
                    if (isinstance(row.VE, float)):
                        txt += '-%s' % str(int(row.VE))
                    if (isinstance(row.CLUB, float)):
                        txt += '\n(%d)' % row.CLUB

                    #if(not np.isnan(row.VE)):
                    #    txt+='-%s'%row.VE
                    #row_cells[3].text = txt
                    c = row_cells[3]
                    if ('R' in row['FLAGS']):
                        txt += '\nrepeat'
                        c._tc.get_or_add_tcPr().append(
                            parse_xml(r'<w:shd {} w:fill="FFFF00"/>'.format(
                                nsdecls('w'))))
                    c.text = txt

                    for k, cell in enumerate(row_cells):
                        cell.width = width[k]

        document.save(fn)
        print('Done writing quiz packet (%s)' % fn)
예제 #54
0
 def get_photo(self):
     photo_folder_name = self.user + "-photo"
     # 进入照片集列表页
     photos_home_elem = self.home_bs.select('table')[2].select(
         'tr')[0].select('td')[1]
     photos_home_url = photos_home_elem.select('a')[0].get('href')
     photos_home_num = photos_home_elem.select('span')[0].getText()
     photos_home_res = self.req.get(photos_home_url, headers=self.headers)
     photos_home_bs = BeautifulSoup(photos_home_res.text, "html.parser")
     # 把照片集全部找出来,最后一个div是翻页
     is_photos_next = True
     photos_current_bs = photos_home_bs
     while is_photos_next:
         photos_elem_list = photos_current_bs.select('div.list')[0].select(
             'div')
         # 遍历照片集
         for photos_elem in photos_elem_list[1:-1]:
             photos_url = photos_elem.select('a')[-1].get('href')
             photos_title = photos_elem.select('a')[-1].getText().strip()
             photos_update = re.split(
                 "\s+",
                 photos_elem.select('span.ns')[0].getText().strip())[1]
             path = photo_folder_name + os.sep + photos_title + photos_update
             if not os.path.exists(path):
                 os.makedirs(path)
             photos_res = self.req.get(photos_url, headers=self.headers)
             photos_bs = BeautifulSoup(photos_res.text, "html.parser")
             # 进入单张浏览页面
             try:
                 photo_list_url = photos_bs.select('div.list')[0].select(
                     'a')[0].get('href')
             except IndexError:
                 # 此照片集内无照片
                 continue
             photo_list_res = self.req.get(photo_list_url,
                                           headers=self.headers)
             photo_list_bs = BeautifulSoup(photo_list_res.text,
                                           "html.parser")
             # 判断是否有下一张,如果有,会继续循环
             is_photo_next = True
             photo_current_bs = photo_list_bs
             id = 0
             while is_photo_next:
                 id += 1
                 photo_title = \
                     re.split("\s+", photo_current_bs.select('div.sec')[2].select('p')[1].getText().strip())[0]
                 # 有可能出现没有标题的图片,用自增的id表示
                 if photo_title == "小图":
                     photo_title = str(id)
                 else:
                     photo_title = str(id) + "-" + photo_title
                 photo_date_str_list = re.split(
                     "\s+|:",
                     photo_current_bs.select('div.sec')[2].select('p')
                     [2].getText().strip())
                 photo_date = photo_date_str_list[1] + photo_date_str_list[
                     2] + ":" + photo_date_str_list[3]
                 photo_location = ""
                 document = Document()
                 document.add_heading(photo_title, 0)
                 document.add_paragraph(photo_date)
                 img_url = photo_current_bs.select('div.sec')[2].select(
                     'p')[1].select('a')[-1].get('href')
                 photo_content = self._get_img_via_url(img_url)
                 try:
                     document.add_picture(photo_content, width=Inches(6))
                 except image.exceptions.UnrecognizedImageError:
                     # img无法下载,forbidden403
                     pass
                 document.add_heading('好友评论', level=1)
                 # 获取评论
                 try:
                     photo_comment_list = photo_current_bs.select(
                         'div.list')[0].select('div')
                     # 查看是否有多页评论
                     # photo_all_comments_url = photo_current_bs.select('div.sec')[-5].a.get('href')
                     photo_all_comments_url = photo_current_bs.find_all(
                         'a', text=re.compile("查看全部评论"))[0].get('href')
                     if photo_all_comments_url:
                         photo_comment_list = self._get_all_comments(
                             photo_all_comments_url)
                     self._process_comments(document, photo_comment_list)
                 except IndexError:
                     # no comments or no comments next tab
                     pass
                 document.add_page_break()
                 document.save(path + os.sep + photo_title + '.docx')
                 # 获取下一页信息
                 try:
                     photo_is_next_list = re.findall(
                         "\d+",
                         photo_current_bs.select('div.sec')[3].select(
                             'span')[-1].getText().strip())
                 except IndexError:
                     # 只有1页的情况下,没有下一页的标签
                     is_photo_next = False
                     continue
                 is_photo_next = True if photo_is_next_list[
                     0] != photo_is_next_list[1] else False
                 if is_photo_next:
                     photo_next_url = photo_current_bs.select(
                         'div.sec')[3].a.get("href")
                     photo_next_res = self.req.get(photo_next_url,
                                                   headers=self.headers)
                     photo_next_bs = BeautifulSoup(photo_next_res.text,
                                                   "html.parser")
                     photo_current_bs = photo_next_bs
         is_photos_next = True if photos_elem_list[-1].select('a')[0].get(
             'title') == "下一页" else False
         if is_photos_next:
             photos_next_url = photos_elem_list[-1].select('a')[0].get(
                 'href')
             photos_next_res = self.req.get(photos_next_url,
                                            headers=self.headers)
             photos_next_bs = BeautifulSoup(photos_next_res.text,
                                            "html.parser")
             photos_current_bs = photos_next_bs
     return photo_folder_name
예제 #55
0
파일: test.py 프로젝트: PozAnta/SystemOrig
import sys
def llenar_inter_plut(nombre_archivo):
    general = pd.read_csv("./archivos/current_general.csv",
                          sep=";",
                          encoding="latin")
    igm = str(general.iloc[0]["igm"])
    if igm == nan: igm = "IGM"
    archivo = Document(nombre_archivo)
    archivo.add_paragraph()
    archivo.add_heading("DESCRIPCIÓN MICROSCÓPICA")
    archivo.add_paragraph()
    subs = [
        "Textura general:", "Otras texturas o texturas especiales:",
        "Descripción de la matriz:"
    ]
    for i in subs:
        p1 = archivo.add_paragraph()
        r1 = p1.add_run(i)
        r1.bold = True
        r1.underline = True
        if i == subs[0]:
            p1.add_run(
                " Mencionar ordenada, clara y correctamente los términos texturales que indican"
                +
                "dimensión relativa de los cristales, tamaños de cristales, cristalinidad, "
                +
                "relaciones mutuas entre cristales,  formas cristalinas o desarrollo relativo de caras de cristales"
            )
        else:
            p1.add_run(" ")
        archivo.add_paragraph()
    archivo.add_page_break()
    archivo.add_paragraph()
    archivo.add_heading("COMPOSICIÓN MINERALÓGICA (% VOL) - " + igm)
    archivo.add_paragraph()
    rows = 12
    tabla_perc = archivo.add_table(rows, 6)
    tabla_perc.style = 'Table Grid'
    for i in range(rows):
        for j in range(6):
            if j % 2 != 0:
                tabla_perc.cell(i, j).width = Cm(1)
            else:
                tabla_perc.cell(i, j).width = Cm(4)
    for i in range(6):
        if i % 2 != 0:
            colum = tabla_perc.columns[i]
            colum.width = Cm(1)
    cells = [0, 1, 2, 3, 4, 4, 0, 2]
    content = [
        "MINERALES \nPRINCIPALES", "%", "MINERALES \nACCESORIOS", "%",
        "MINERALES DE ALTERACIÓN", "MINERALES DE INTRODUCCIÓN", "TOTAL",
        "TOTAL"
    ]

    for i in range(len(cells)):
        if i > 5:
            para = tabla_perc.cell(11, cells[i]).paragraphs[0]
        elif i == 5:
            para = tabla_perc.cell(6, cells[i]).paragraphs[0]
        else:
            para = tabla_perc.cell(0, cells[i]).paragraphs[0]
        r1 = para.add_run(content[i])
        r1.bold = True
    tabla_perc.cell(0, 4).merge(tabla_perc.cell(0, 5))
    tabla_perc.cell(6, 4).merge(tabla_perc.cell(6, 5))

    archivo.add_paragraph()
    clas_roc = archivo.add_paragraph()
    run = clas_roc.add_run("CLASIFICACIÓN DE LA ROCA ")
    run.bold = True
    run.underline = True
    r2 = clas_roc.add_run("(Basada en Streckeisen, 1976):")
    r2.underline = True
    clas_roc.add_run(" La clasificación")
    archivo.add_paragraph()
    archivo.add_heading("DESCRIPCIÓN MICROSCÓPICA DE MINERALES")
    archivo.add_paragraph()
    p1 = archivo.add_paragraph()
    r1 = p1.add_run("Mineral 1:")
    r1.bold = True
    r1.underline = True
    p1.add_run(
        " Descripción concisa y completa de rasgos generales y particulares," +
        "sin olvidar tamaño, forma, color, distribución, relaciones texturales, "
        + "extinción, clivaje, etc")
    archivo.add_paragraph()
    archivo.add_heading("OBSERVACIONES")
    archivo.add_paragraph()
    archivo.save(nombre_archivo)
예제 #57
0
    def showDialog2(self):

        self.all_form = self.all_form+self.text_lst+self.text_lst_2
        document = Document()
        p = document.add_paragraph('ДОГОВОР купли – продажи квартиры № %(10)s '''% {"10":self.all_form[10]})
        p = document.add_paragraph('г. Санкт-Петербург                    	   «__» ____________ 201__ года')
        p = document.add_paragraph('Общество с ограниченной ответственностью «Карат», являющееся юридическим лицом по законодательству'
                                        ' Российской Федерации, зарегистрированное в МИ МНС № 11 по Санкт-Петербургу Свидетельством '
                                        'о государственной регистрации ЮЛ серия 78 № 004629954 от 31.10.2003 года, ОГРН 1037869011421, '
                                        'ИНН 7842003710, КПП 780601001, местонахождение: 195112, г. Санкт-Петербург, Малоохтинский пр., д. 61,'
                                        ' литера А, пом. 61, в лице генерального директора Осипова Дмитрия Вячеславовича, действующего на'
                                        ' основании Устава, именуемое далее «Продавец», и')

        p = document.add_paragraph('Гражданин Российской Федерации %(2)s %(3)s %(4)s %(19)s года рождения, место рождения:%(5)s, пол: %(0)s, паспорт %(6)s %(7)s выдан %(20)s г. '
                                        '%(8)s, зарегистрированный по адресу (адрес для уведомлений): %(9)s, именуемый далее «Покупатель», с другой стороны, '
                                        'заключили настоящий Договор о нижеследующем'% {"0":self.all_form[0], "2":self.all_form[2],"3":self.all_form[3],
                                                                                        "4":self.all_form[4],"5":self.all_form[5],"6":self.all_form[6],
                                                                                        "7":self.all_form[7],"8":self.all_form[8],"9":self.all_form[9],
                                                                                        "19":self.all_form[19],"20":self.all_form[20]})
        p = document.add_paragraph('Продавец продал, а Покупатель купил %(1)sкомнатную квартиру, находящуюся по адресу: гор. Санкт-Петербург, г. Сестрорецк,'
                                   'Приморское шоссе, д. 293, кв. %(10)s'%{"1":self.all_form[1],"10":self.all_form[10]},style='ListNumber')
        
        p = document.add_paragraph('Указанная квартира (кадастровый номер: %(16)s) расположена на %(11)s этаже жилом 10-17-ти этажном доме'
                                   'со встроенными помещениями 2014 года постройки. Общая площадь квартиры составляет – %(13)s кв.м.;'
                                   'из нее жилая площадь – %(14)s кв.м.'%{"16":self.all_form[16], "11":self.all_form[11],"13":self.all_form[13],
                                                                          "14":self.all_form[14]},style='ListNumber')
        
        p = document.add_paragraph('Отчуждаемая квартира принадлежит Обществу с ограниченной ответственностью «Карат» на праве собственности,'
                                   'о чем в Едином государственном реестре прав на недвижимое имущество и сделок с ним'
                                   '%(21)s года сделана запись регистрации № %(17)s.'% {"17":self.all_form[17], "21":self.all_form[21]},style='ListNumber')
        
        p = document.add_paragraph('Указанная квартира по договоренности сторон продается и покупается за сумму %(18)s рублей 00 копеек. Взаиморасчеты произведены'
                                   'в полном объеме между Сторонами до подписания настоящего Договора. Стороны финансовых и иных претензий друг к другу не имеют.'%
                                   {"18":self.all_form[18]},style='ListNumber')
        
        p = document.add_page_break()

        p = document.add_paragraph('АКТ ПРИЕМА-ПЕРЕДАЧИ КВАРТИРЫ  № %(10)s '''% {"10":self.all_form[10]})
        p = document.add_paragraph('г. Санкт-Петербург                    	   «__» ____________ 201__ года')
        p = document.add_paragraph('Общество с ограниченной ответственностью «Карат», являющееся юридическим лицом по законодательству'
                                        ' Российской Федерации, зарегистрированное в МИ МНС № 11 по Санкт-Петербургу Свидетельством '
                                        'о государственной регистрации ЮЛ серия 78 № 004629954 от 31.10.2003 года, ОГРН 1037869011421, '
                                        'ИНН 7842003710, КПП 780601001, местонахождение: 195112, г. Санкт-Петербург, Малоохтинский пр., д. 61,'
                                        ' литера А, пом. 61, в лице генерального директора Осипова Дмитрия Вячеславовича, действующего на'
                                        ' основании Устава, именуемое далее «Продавец», и')

        p = document.add_paragraph('Гражданин Российской Федерации %(2)s %(3)s %(4)s %(19)s года рождения, место рождения:%(5)s, пол: %(0)s, паспорт %(6)s %(7)s выдан %(20)s г. '
                                        '%(8)s, зарегистрированный по адресу (адрес для уведомлений): %(9)s, именуемый далее «Покупатель», с другой стороны, '
                                        'другой стороны, составили настоящий акт приема-передачи квартиры № %(10)s в соответствии с договором купли-продажи '
                                        'квартиры № %(10)s от «__» ______ 201__ года.'% {"0":self.all_form[0], "2":self.all_form[2],"3":self.all_form[3],
                                                                                        "4":self.all_form[4],"5":self.all_form[5],"6":self.all_form[6],
                                                                                        "7":self.all_form[7],"8":self.all_form[8],"9":self.all_form[9],
                                                                                        "10":self.all_form[10],"19":self.all_form[19],"20":self.all_form[20]})
        
        p = document.add_paragraph('Квартира передается в том виде и состоянии, в котором она находится на момент передачи ее Покупателю. С момента подписания'
                                   'настоящего акта сторонами Продавец передает Покупателю, а Покупатель принимает квартиру, расположенную по адресу: '
                                   'г. Санкт-Петербург, г. Сестрорецк, Приморское шоссе, д. 293, следующих характеристик:',style='ListNumber')
        
        table = document.add_table(rows=2, cols=6)
        hdr_cells = table.rows[0].cells
        hdr_cells[0].text = 'Номер квартиры'
        hdr_cells[1].text = 'Количество комнат'
        hdr_cells[2].text = 'Этаж'
        hdr_cells[3].text = 'Общая жилая площадь по данным ПИБ, кв.м.'
        hdr_cells[4].text = 'Общая площадь с учетом приведенной площади балкона, лоджии, кв.м.'
        hdr_cells[5].text = 'Общая внутренняя площадь квартиры, кв.м.'

        hdr_cells = table.rows[1].cells
        hdr_cells[0].text = ' '
        hdr_cells[1].text = ' '
        hdr_cells[2].text = ' '
        hdr_cells[3].text = ' '
        hdr_cells[4].text = ' '
        hdr_cells[5].text = ' '
        
        document.save('demo.docx')

        self.reply3 = QtWidgets.QMessageBox.question(self, 'Сохранение документа','Документ успешно сохранен!', QMessageBox.Yes)
예제 #58
0
def BuildWordFile(strFilename, path):
    try:  # 加入try catch
        #准备文档
        filename = strFilename
        document = Document()
        xml = etree.parse(path)
        root = xml.getroot()  # 获取根节点
        list = root.getchildren()
        types = list[0]
        lstSchema = types.getchildren()
        schema = lstSchema[0]
        #准备word数据
        apiCount = 1
        #文件标题
        heading = document.add_heading(filename + "接口说明文档", 0)
        #新增样式(第一个参数是样式名称,第二个参数是样式类型:1代表段落;2代表字符;3代表表格)
        style = document.styles.add_style('style name 1', 2)
        style.font.color.rgb = RGBColor(165, 27, 71)

        style2 = document.styles.add_style('style name 2', 2)
        style2.font.size = 11
        style2.font.name = "Arial"
        #参数用的样式
        style3 = document.styles.add_style('style name 3', 3)
        style3.font.size = 11
        style3.font.name = "Consolas"

        #先生成一个汇总表格
        document.add_paragraph(u'接口调用说明和清单', style='Heading 3')

        totalRow = 1
        for api in schema.getchildren():
            lstComplexType = api.getchildren()
            complexType = lstComplexType[0]
            lstSequence = complexType.getchildren()
            if len(lstSequence) != 0:
                sequence = lstSequence[0]
                lstElement = sequence.getchildren()
                if len(lstElement) != 0:
                    #生成表格
                    totalRow = totalRow + 1
                    #break;

        #生成表格
        totalTable = document.add_table(rows=totalRow,
                                        cols=3,
                                        style='Table Grid')
        totalRowIndex = 1
        for api in schema.getchildren():
            lstComplexType = api.getchildren()
            complexType = lstComplexType[0]
            lstSequence = complexType.getchildren()
            if len(lstSequence) != 0:
                sequence = lstSequence[0]
                lstElement = sequence.getchildren()
                if len(lstElement) != 0:
                    apiName = api.get("name", "")
                    totalTable.cell(0, 0).text = "序号"
                    totalTable.cell(0, 1).text = "接口"
                    totalTable.cell(0, 2).text = "说明"
                    totalTable.cell(totalRowIndex, 0).text = str(totalRowIndex)

                    #汇总添加明细的超链接
                    ptotalTableApiName = totalTable.cell(totalRowIndex,
                                                         1).paragraphs[0]
                    add_hyperlink(ptotalTableApiName, apiName,
                                  '#' + str(totalRowIndex) + "." + apiName)
                    #totalTable.cell(totalRowIndex, 1).text =apiName

                    #翻译接口名字得到接口说明
                    description = myTranslator(apiName)
                    totalTable.cell(totalRowIndex, 2).text = description
                    print(
                        str(totalRowIndex) + "添加汇总:" + apiName + " " +
                        description)
                    totalRowIndex = totalRowIndex + 1
                    #测试
                    '''
                 if totalRowIndex==5:
                     break
                 '''

        for api in schema.getchildren():
            #获取参数
            lstComplexType = api.getchildren()
            complexType = lstComplexType[0]
            lstSequence = complexType.getchildren()
            if len(lstSequence) != 0:
                sequence = lstSequence[0]
                lstElement = sequence.getchildren()
                if len(lstElement) != 0:
                    apiName = api.get("name", "")
                    print("接口方法:", apiName)  # 输出节点的标签名
                    #添加接口名称
                    methodParagraph = document.add_paragraph(str(apiCount) +
                                                             "." + apiName,
                                                             style='Heading 3')
                    apiCount = apiCount + 1
                    #run=methodParagraph.add_run()
                    #run.font.bold = True
                    #run.style='IntenseQuote'
                    #增加引用
                    #document.add_paragraph('Intense quote', style='Intense Quote')

                    descriptionParagraph = document.add_paragraph("说明:")
                    #翻译接口名字得到接口说明
                    description = myTranslator(apiName)
                    descriptionParagraph.add_run(description)

                    requestParagraph = document.add_paragraph("请求")
                    #requestParagraph.add_run("请求",style=style2)
                    #生成表格
                    requestTable = document.add_table(rows=2,
                                                      cols=2,
                                                      style='Table Grid')
                    requestTable.cell(0, 0).text = "方法"
                    requestTable.cell(0, 1).text = "URL"
                    requestTable.cell(1, 0).text = "POST"
                    requestTable.cell(1, 1).text = apiName

                    paraParagraph = document.add_paragraph("参数:")
                    #paraParagraph.add_run("参数:",style=style2)

                    #生成表格
                    table = document.add_table(rows=len(lstElement) + 1,
                                               cols=4,
                                               style="Table Grid")
                    table.cell(0, 0).text = "传入类型"
                    table.cell(0, 1).text = "参数"
                    table.cell(0, 2).text = "值类型"
                    table.cell(0, 3).text = "说明"
                    row = 1
                    for element in lstElement:
                        print("参数:", element.get("name", ""),
                              element.get("type", ""))
                        table.cell(row, 0).text = "POST"
                        table.cell(row, 1).text = element.get("name", "")
                        table.cell(row, 2).text = element.get("type", "")
                        #翻译参数名
                        paraName = myTranslator(element.get("name", ""))
                        table.cell(row, 3).text = paraName
                        row = row + 1
                returnParagraph = document.add_paragraph("返回:")
                #returnParagraph.add_run("返回:",style=style2)
                #生成结果表格
                responseTable = document.add_table(rows=6,
                                                   cols=3,
                                                   style='Table Grid')
                responseTable.cell(0, 0).text = "状态"
                responseTable.cell(0, 1).text = "返回"
                responseTable.cell(0, 2).text = "说明"

                responseTable.cell(1, 0).text = "200"
                responseTable.cell(1, 1).text = "0"
                responseTable.cell(2, 0).text = "403"
                responseTable.cell(3, 0).text = "400"
                responseTable.cell(4, 0).text = "401"
                responseTable.cell(5, 0).text = "500"
                #测试
                '''
              if apiCount==5:
                 break
              '''

        document.add_page_break()
        document.save("c:\\" + filename + "接口说明文档.docx")
        print("生成文档完成," + "c:\\" + filename + "接口说明文档.docx")
    except Exception as e:
        print(e)  # 加入打印
예제 #59
0
def write_report(file_name):

    document = Document()
    document.add_heading('User Stories', level=1)

    styles = document.styles
    us_style = styles.add_style("Panalysis User Stories", WD_STYLE_TYPE.TABLE)
    us_style.base_style = styles["Medium Grid 1 Accent 1"]

    rr_style = styles.add_style("Panalysis Reporting Requirement", WD_STYLE_TYPE.TABLE)
    rr_style.base_style = styles["Medium List 2 Accent 1"]

    table1 = document.add_table(rows=1, cols=4, style=us_style)

    table1.columns[0].width = Cm(3)
    table1.columns[1].width = Cm(12)
    table1.columns[2].width = Cm(5)
    table1.columns[3].width = Cm(4)

    hdr_cells = table1.rows[0].cells
    hdr_cells[0].text = 'Number'
    hdr_cells[1].text = 'Details'
    hdr_cells[2].text = 'Priority'
    hdr_cells[3].text = 'Reporting Requirements'

    for i in doc_items['user_stories']:

        row_cells = table1.add_row().cells
        row_cells[0].text = str(i.id)
        row_cells[1].text = str(i.description)
        row_cells[2].text = str(i.priority)
        row_cells[3].text = str(i.reqs)


    document.add_page_break()

    document.add_heading('Reporting Requirements', level=1)

    for i in doc_items['reporting_requirements']:

        document.add_heading(str(i.id) + ": " +  i.title, level=2)
        table2 = document.add_table(rows=1, cols=2, style=rr_style)

        table2.columns[0].width = Cm(2)
        table2.columns[1].width = Cm(15)

        requirements_table = ["Description","Purpose","User Stories","Priority","Data Source","Dimensions","Metrics","Segments","Aggregation","Requires Custom Report"]
        for x in requirements_table:
            row_cells = table2.add_row().cells
            row_cells[0].text = str(x) + ":"

            if x == "Description":
                row_cells[1].text = i.description
            elif x == "Purpose":
                row_cells[1].text = i.purpose
            elif x == "User Stories":
                row_cells[1].text = str(i.user_story_id)
            elif x == "Priority":
                row_cells[1].text = i.priority
            elif x == "Data Source":
                row_cells[1].text = i.data_source
            elif x == "Dimensions":
                row_cells[1].text = i.dimensions
            elif x == "Metrics":
                row_cells[1].text = i.metrics
            elif x == "Segments":
                row_cells[1].text = i.segment
            elif x == "Aggregation":
                row_cells[1].text = i.aggregation
            elif x == "Requires Custom Report":
                row_cells[1].text = i.custom_report


    document.save(file_name)
예제 #60
0
def report_generation_continuous(self):
    document = Document()
    document.add_heading('Data Analysis Report', 0)

    document.add_heading('Raw data summary', level=1)

    p1 = document.add_paragraph('The underlying data has ')
    p1.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
    p1.add_run(str(len(self.y)))
    p1.add_run(' observations with ')
    if self.model_name != '9':
        p1.add_run(str(len(self.X[0])))
    else:
        p1.add_run('1')
    p1.add_run(
        ' variables. The raw data was split into training and testing data using '
    )
    p1.add_run(self.report_partition)
    p1.add_run(', which resulted in a training data size of ')
    p1.add_run(str(len(self.y_train)))
    p1.add_run(' and a testing data size of ')
    p1.add_run(str(len(self.y_test)))
    p1.add_run('. ')
    p1.add_run(self.report_model)
    if (self.lamNum != 0):
        p1.add_run(
            ' was used as the for data analysis and its tuning parameters were selected using '
        )
        p1.add_run(self.report_tuning)
    else:
        p1.add_run(' was used as the for data analysis')
    p1.add_run(' with the training dataset.')

    document.add_heading('Data analysis summary', level=1)

    p2 = document.add_paragraph(
        'The goodness-of-fit measured in adj R-squared is ')
    p2.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
    p2.add_run(str(self.adj_rsquared))
    if self.model_name != '6':
        p2.add_run(
            '. Based on the best model selected, the prediction error on the testing data is '
        )
        p2.add_run(str(self.rmse_test_final))
    else:
        p2.add_run(
            '. Based on the best model selected, the prediction accuracy on the testing data is '
        )
        p2.add_run(str(self.testscore))
    p2.add_run('. The residual plot is attached in the following section')

    document.add_heading('The performance measure table', level=1)

    if self.model_name != '6':
        performance_measure_table = [[1, "goodness-of-fit", self.adj_rsquared],
                                     [
                                         2, "training rmse",
                                         self.rmse_train_final
                                     ],
                                     [3, "testing rmse", self.rmse_test_final]]
    else:
        performance_measure_table = [
            [1, "goodness-of-fit", self.adj_rsquared],
            [2, "training accuracy", self.trainscore],
            [3, "training type I error", self.T1Error],
            [4, "training type II error", self.T2Error],
            [5, "testing accuracy", self.testscore],
            [6, "training type I error", self.T1Error1],
            [7, "training type II error", self.T2Error1]
        ]
    table = document.add_table(rows=1, cols=3)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = 'Performance measure index'
    hdr_cells[1].text = 'Performance measure name'
    hdr_cells[2].text = 'Value'
    for item in performance_measure_table:
        row_cells = table.add_row().cells
        row_cells[0].text = str(item[0])
        row_cells[1].text = str(item[1])
        row_cells[2].text = str(item[2])

    document.add_heading('The residual plot', level=1)
    if self.model_name == '7':
        for i in range(self.y_train.shape[1]):
            document.add_heading('task ' + str(i + 1), level=2)
            document.add_picture('./' + self.folderName + '/residual_plot' +
                                 str(i) + '.png',
                                 height=Inches(4),
                                 width=Inches(5.5))
    else:
        document.add_picture('./' + self.folderName + '/residual_plot.png',
                             height=Inches(4),
                             width=Inches(5.5))
    if (self.lamNum != 0):
        document.add_heading('The tuning plot', level=1)
        document.add_picture('./' + self.folderName +
                             '/parameter_tuning_plot.png',
                             height=Inches(4),
                             width=Inches(5.5))

    document.add_page_break()
    document.save('./' + self.folderName + '/report_demo.docx')