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")
class DocXRenderer(mistune.Renderer): def __init__(self, *largs, **kargs): self.doc = Document() self.clist = None super(DocXRenderer, self).__init__(*largs, **kargs) def list_item(self, text): return "{}\n".format(text) def list(self, body, ordered=True): if ordered: style = "ListNumber3" else: style = "ListBullet" for i in body.rstrip().split("\n"): self.doc.add_paragraph(i, style) return '' def header(self, text, level, raw=None): self.doc.add_heading(text, level) return '' def paragraph(self, text): self.doc.add_paragraph(text, style=None) return ''
def download(rfq_id): # send_file? document = Document() session = Session() rfq = session.query(RFQ).filter_by(id=rfq_id).first() print rfq title = "RFQ for " + rfq.agency document.add_heading("RFQ", 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") doc_name = "RFQ_" + str(rfq_id) + ".docx" file_path = os.path.join(doc_name, "downloads") document.save(file_path) # download_folder = os.path.join(current_app.root_folder, "downloads") return send_from_directory(directory="downloads", filename=doc_name)
def convert_pdf(path='provide path here', format='text', codec='utf-8'): rsrcmgr = PDFResourceManager() retstr = BytesIO() laparams = LAParams() if format == 'text': device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams) else: raise ValueError('Please provide the format to extract') fp = open(path, 'rb') interpreter = PDFPageInterpreter(rsrcmgr, device) maxpages = 500 #mention the maximum pages here (Note: Large number of pages will decrease the performance.) caching = True page_numbers=set() for page in PDFPage.get_pages(fp, page_numbers, maxpages=maxpages,caching=caching, check_extractable=True): interpreter.process_page(page) text = retstr.getvalue().decode() fp.close() device.close() retstr.close() bulletins_data = re.findall('•([^•]+)*', str(text)) list_of_bullet_points = [] json_dict = {} for points in bulletins_data: list_of_bullet_points.append(points) json_dict['bulletins'] = list_of_bullet_points json_data= json.dumps(json_dict) parsed = json.loads(json_data) final_data = json.dumps(parsed, indent=4, sort_keys=True) #creates a pretty json with the data extracted document = Document() # creates a new document document.add_heading('Bulletins data in the PDF') document.add_paragraph(str(final_data)) document.save('json_data.docx') # saves it to the filesystem os.startfile("json_data.docx") # will open the file return ''
def exportPayInfo(self): """ 导出出付费信息 """ title = '%s[%s]' % (self.username, datetime.strftime(datetime.now(), "%Y-%m-%d")) reserveInfo = pitcher.getReserveInfo() c1 = reserveInfo[u'状态'] == u'未确认' c2 = reserveInfo[u'最后确认时间'].apply(parser.parse) > datetime.now() reserveInfo = reserveInfo[c1 & c2] document = Document() document.add_heading(title) for i, row in reserveInfo.iterrows(): document.add_heading(u'票项%d' % (i + 1), level=1) document.add_paragraph(text=u'航线: ' + row[u'航线']) document.add_paragraph(text=u'航班时间: ' + row[u'航班时间']) document.add_paragraph(text=u'人数: ' + row[u'人数']) document.add_paragraph(text=u'金额: ' + row[u'金额']) document.add_paragraph(text=u'最后确认时间: ' + row[u'最后确认时间']) filename = tempfile.mktemp(suffix='.jpg',prefix='tmp_') with open(filename, 'wb') as f: orderNumber = pitcher.getOrderNumber(row[u'预订ID']) qrcode = pitcher.getWeixinPayQrcode(orderNumber) f.write(qrcode) document.add_picture(filename, width=Inches(1)) time.sleep(self.normalWaitingSecond) filename = tempfile.mktemp(suffix='.docx',prefix=title + '_') document.save(filename) # 发送邮件 send_mail(settings.MAIL_LIST, title, u'见附件', [filename])
class XQHTMLParser(HTMLParser): def __init__(self, docfile): HTMLParser.__init__(self) self.docfile = docfile self.doc = Document(docfile) self.myclient = HTMLClient() self.text = '' self.title = False self.isdescription = False self.picList=[] def handle_starttag(self, tag, attrs): #print "Encountered the beginning of a %s tag" % tag self.title = False self.isdescription = False if re.match(r'h(\d)', tag): self.title = True if tag == "img": if len(attrs) == 0: pass else: for (variable, value) in attrs: if variable == "src": picdata = self.myclient.GetPic(value.split('!')[0]) if picdata == None: pass else: pictmp = value.split('/')[-1].split('!')[0] picfix = value.split('/')[-1].split('!')[-1] with open(pictmp, 'wb') as pic: pic.write(bytes(picdata)) pic.close() #if os.path.getsize(pictmp) < 90000: try: if picfix[0:1] == 'c': self.doc.add_picture(pictmp, width=Inches(4.5)) else: self.doc.add_picture(pictmp)#, width=Inches(2.25)) except docx.image.exceptions.UnexpectedEndOfFileError as e: print(e) self.picList.append(pictmp) if tag == 'script': self.isdescription = True def handle_data(self, data): if self.title == True: if self.text != '': self.doc.add_paragraph(self.text) self.text = '' self.doc.add_heading(data, level=2) if self.isdescription == False: self.text += data def handle_endtag(self, tag): #if tag == 'br' or tag == 'p' or tag == 'div': if self.text != '': self.doc.add_paragraph(self.text) self.text = '' def complete(self, html): self.feed(html) self.doc.save(self.docfile) for item in self.picList: if os.path.exists(item): os.remove(item)
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)
def create(title): global DOC_NAME DOC_NAME = title document = Document() document.add_heading(DOC_NAME, 0) document.save('%s.docx' % DOC_NAME) return document
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)
def get(name): saveFile = os.getcwd()+"/"+name try: doc = Document() doc.add_heading("HEAD".decode('gbk'),0) doc.add_paragraph("HEAD CONTENT".decode('gbk')) doc.save(saveFile) except : print("error")
def writeDoc(title,content): docName = title+'.docx' document = Document() document.add_heading(title, 0) document.add_paragraph(content) document.save(docName)
def __init__(self, title, content, sourceUrl, path): document = Document() document.add_heading(title, 0) document.add_paragraph( content ) document.add_paragraph( '\n') document.add_paragraph( 'Source: ' + sourceUrl) if not os.path.exists(path): os.makedirs(path) document.save(path+'/'+self.replaceForbiddenChars(title)+'.docx')
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
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')
def writeDoc(docTitle, feed, fileName): # Setting up word doc for file writing document = Document() document.add_heading(fileName, 0) # Writing it out document.add_paragraph(unicode(feed, 'utf-8')) try : document.save('I:\dev_JC\_Python\Data_Pull\WD\\' + fileName + '.docx') except IOError: document.save('I:\dev_JC\_Python\Data_Pull\WD\\' + "Bad_Name" + '.docx')
class HoroDocument(): def generate(self, content): self.doc = Document() for item in content: self.doc.add_heading(item['section_title'], level=1) for para in item['paragraph']: self.doc.add_heading(para['title'], level=3) self.doc.add_paragraph(para['content']) def save(self, filename): self.doc.save(filename)
def doit(): host = '192.168.1.254' user = '******' password = '******' database = 'renrenbx' mysql_init(mysql_host = host, mysql_database = database, mysql_user = user, mysql_password = password) tables = {} for column in table_schema(database): tables[column['TABLE_NAME']] = {'info':column,'columns':[]} for column in table_colume(database): tables[column['TABLE_NAME']]['columns'] += [column] document = Document() document.add_heading(database, 0) i = 0 max = len(tables) for key in sorted(tables.keys()): i = i + 1 value = int(round((i * 1.0) / max * 100)) sys.stdout.write(' [' + '#' * i + '] %s%%' % value + '\r') sys.stdout.flush() document.add_heading(key, 1) table_engine = tables[key]['info']['ENGINE'] paragraph = document.add_paragraph() paragraph.add_run(table_engine).bold = True table_comment = tables[key]['info']['TABLE_COMMENT'] paragraph = document.add_paragraph() paragraph.add_run(table_comment if table_comment else u'无注释').bold = True table = document.add_table(rows = 1, cols = 4) 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'注释' for column in tables[key]['columns']: row_cell = table.add_row().cells row_cell[0].text = column['COLUMN_NAME'] row_cell[1].text = column['COLUMN_KEY'] if column['COLUMN_KEY'] else '-' row_cell[2].text = column['COLUMN_TYPE'] row_cell[3].text = column['COLUMN_COMMENT'] if column['COLUMN_COMMENT'] else '-' document.save('%s-%s.docx' % (database,datetime.datetime.now().strftime("%Y%m%d%H")))
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')))
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()
def create_doc(heading_pre, date_as_string): """ Creates a document with an empty table and given heading :param heading_pre: string, the prefix of the heading (e.g. 'Conflicts ') :param date_as_string: string, the date as a string :return: """ document = Document() document.add_heading(heading_pre + date_as_string, 0) table = document.add_table(rows=1, cols=4) headings = table.rows[0].cells create_headings(headings) return document
def finish_report(self, arg, text, extra): easygui.msgbox("Reached", title="Warning") remove = set(self.lst) sorted_list = list(remove) document = Document() headings = ['All Files', 'File System Info', 'Deleted Files', 'Deleted Folders', 'Partition Info'] for entry in sorted_list: print entry document.add_heading(headings[entry]) document.add_paragraph(self.storage_array[entry + 1]) document.save('test.docx')
def generatedocx(logs, quarter): # This function will generate the .docx file for the report, given the list # of logs in the form of the named tuple. #create the document report = Document() logs.sort(key=lambda tup: tup[2]) testlogs = {} for log in logs: if log.psa not in testlogs: testlogs[log.psa] = {} if log.date not in testlogs[log.psa]: testlogs[log.psa][log.date] = [] testlogs[log.psa][log.date].append(log.time) #Generate the title if date.today().month == 1: report.add_heading('KTEQ-FM Quarterly Issues Report Q' + str(quarter) + ' '+ str(date.today().year-1), level=0) else: report.add_heading('KTEQ-FM Quarterly Issues Report Q' + str(quarter) + ' '+ str(date.today().year), level=0) report.add_paragraph('This document is the quarterly Community Issues Report for KTEQ-FM. It details a number of community issues discussed during programming throughout the quarter, and lists public service announcements that support these issues. This list contains all of the public service announcements played on air by live DJs. For a complete list, including automated public service announcements, contact KTEQ-FM management at [email protected]') table = report.add_table(rows=1, cols=3) hdr = table.rows[0].cells hdr[0].text = 'Date Played' hdr[1].text = 'Time Played' hdr[2].text = 'PSA Title' for entry in logs: row = table.add_row().cells row[0].text = str(entry.date) row[1].text = str(entry.time) row[2].text = entry.psa '''for psa in testlogs: report.add_heading(psa, level=1) table = report.add_table(rows=len(testlogs[psa]), cols=2) for psadate in testlogs[psa]: row = table.add_row().cells row[0].text = str(psadate) row[1].text = str(testlogs[psa][psadate])''' reportdir = 'reports/' + str(date.today().year) if not os.path.exists(reportdir): os.makedirs(reportdir) outputfile = reportdir + '/Q' + str(quarter) + '_Issues.docx' report.save(outputfile)
def write_test_result_report_word(result_report): image_path = sys_tools.base_path + '\\auto_results\\screenshots\\' + result_report.screen_shot word_result_path = sys_tools.base_path + '\\auto_results\\test_results\\' + settings.test_result_file_name_word # image_path = '../auto_results/screenshots/' + result_report.screen_shot # word_result_path = '../auto_results/test_results/' + settings.test_result_file_name_word if os.path.exists(word_result_path): document = Document(word_result_path) else: document = Document() document.add_heading(result_report.report_name + ': ' + result_report.report_test_result.__str__() + '-' + result_report.browser.__str__(), level=1) document.add_paragraph(text='Test Result: ' + result_report.msg) document.add_picture(image_path, width=Inches(4.5)) document.save(word_result_path)
def transclusionDOCX(templatefilepath, resultDocumentDirectoryPath, dataEntities): if not os.path.isfile(templatefilepath): return False TransclusionId = uuid.uuid1(); TransclusionDocumentNumber = 1; for dataEntity in dataEntities: resultDocumentPath = "{0}\\{1}_{2}.docx".format(resultDocumentDirectoryPath, TransclusionId, TransclusionDocumentNumber) document = Document() document.add_heading(dataEntity["id"], 0) with open(templatefilepath,"r") as template_file: for line in template_file: document.add_paragraph(line.format(**dataEntity)) document.save(resultDocumentPath) TransclusionDocumentNumber+=1 return True
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(''', "'").replace(' ', ' ') document.add_paragraph(summary) document.add_page_break() document.save('jobs_EZSearch.docx')
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')
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)
def createAgenda(projKey, slackChan=None, gAuthCode=None, chapter=None): # Needs updating if path changes from docx import Document ut.info("function: createAgenda") projects = {"debug": "54999242167362", "agenda": "47058473474991"} project_url = "https://app.asana.com/api/1.0/projects/{0}/tasks".format(projects[projKey]) drive = authDrive(gAuthCode) fi_name = "agendas/lulaa_weekly_agenda_{0.year}-{0.month}-{0.day}.docx".format(ut.timeNow()) asana_auth_token = chapter["integrations"]["asana"]["auth_token"] agenda_doc = Document() agenda_doc.add_heading(heading, 0) agenda_doc.add_paragraph(createDate).bold = True writeAgenda(asana_auth_token, project_url, agenda_doc, fi_name) uploadToDrive(drive, fi_name, slackChan, chapter)
def clean_write(answers): """Writes answers to word tables, original text, POS-filtered words, Counts for each POS """ document = Document() #microsoft word format document.add_heading('Listings Responses and Word Counts', 0) document.add_paragraph( 'Image Descriptions and Reminded', 'ListBullet') #def tag_count(answers): image_counts = [] for i in range(len(answers)): image_counts.append(Counter({})) document.add_paragraph( 'Image Descriptions and Reminded', style='ListBullet') for j in [0,1]: #do table = document.add_table(rows=1, cols=3) hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Cleaned Response Text' hdr_cells[1].text = 'Usable Words' hdr_cells[2].text = 'Word Counts' for k in range(len(answers[i][j])): row_cells = table.add_row().cells txt = answers[i][j][k] txt = txt.replace(',','') txt = txt.replace('.','') txt = txt.replace('-',' ') txt = txt.replace('/',' ') txt=txt.lower() row_cells[0].text = txt words = nltk.word_tokenize(txt) tags= nltk.pos_tag(words) word_bag = [] tag_bag = [] keep_tags = {'NN','NNS','NNP','NNPS','JJ','JJR','JJS','RB','RBR','RBS'} for tag in tags: if tag[1] in keep_tags: word_bag.append(tag[0]) tag_bag.append(tag[1]) row_cells[1].text = str(word_bag) counts = Counter(tag_bag) POS = Counter(tag_bag).most_common(10) image_counts[i] += counts row_cells[2].text = str(POS) answers[i][j][k] = word_bag document.save('response_&_wordcount.docx')
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)
def profile_to_docx_report(self): # create docx report from profile's relevant parameters create_dir(PATH_REPORTS) if self.profile_not_empty(): heading = self.facebook_uid if self.profile_name: heading = self.profile_name contact_info, facebook_details, facebook_activity = self.set_data_to_report( ) document = Document() document.add_heading("FB Profile Report - %s" % heading, 1) if self.profile_photo and '.jpg' in self.profile_photo: # document.add_picture(self.profile_photo, width=Inches(1.25)) pic_added = try_add_pic(document, self.profile_photo, width=Inches(2.25)) if not pic_added: try_add_pic(document, self.profile_photo, width=Inches(2.25), re_save=True) document.add_heading("Facebook Contact Info & Social Accounts:", 2) add_paragraph_from_list(document, contact_info) document.add_heading("Facebook Details:", 2) add_paragraph_from_list(document, facebook_details) add_paragraph_from_list( document, [('Security Friends: %s' % self.security_friends).replace( 'None', "X")]) add_paragraph_from_list( document, [('Relevant Groups: %s' % self.relevant_groups).replace( 'None', "X")]) add_paragraph_from_list( document, [('Photo Status: %s' % self.pics_on_web).replace('None', "X")]) document.add_heading("Facebook Activity:", 2) add_paragraph_from_list(document, facebook_activity) document.add_heading("Similarity With Other Profiles:", 2) similarity_with_others = self.str_similarity_with_others( doc=document) add_paragraph_from_list(document, similarity_with_others.split('\n\n')) count = 0 if self.found_on_web_screenshot: count += 1 document.add_page_break() document.add_heading( "Appendix %d - the photo is found on web:" % count, 2) try_add_pic(document, self.found_on_web_screenshot, width=Inches(6.25)) # document.add_picture(self.found_on_web_screenshot, width=Inches(6.25)) if self.groups_donut_path and os.path.exists( self.interests_donut_path): count += 1 document.add_heading("Appendix %d - profile's groups:" % count, 2) try_add_pic(document, self.groups_donut_path, width=Inches(6.25)) if self.interests_donut_path and os.path.exists( self.interests_donut_path): count += 1 document.add_heading( "Appendix %d - profile's interests (pages categories):" % count, 2) try_add_pic(document, self.interests_donut_path, width=Inches(6.25)) if self.friends_donut_path and os.path.exists( self.friends_donut_path): count += 1 document.add_heading( "Appendix %d - profile's friends:" % count, 2) try_add_pic(document, self.friends_donut_path, width=Inches(6.25)) document.save( os.path.join(PATH_REPORTS, '%s report.docx' % heading))
from docx import Document from docx.shared import Inches 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='Intense Quote') document.add_paragraph('first item in unordered list', style='List Bullet') document.add_paragraph('first item in ordered list', style='List Number') document.add_picture('monty-truth.png', width=Inches(1.25)) records = ((3, '101', 'Spam'), (7, '422', 'Eggs'), (4, '631', 'Spam, spam, eggs, and spam')) 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 qty, id, desc in records: row_cells = table.add_row().cells row_cells[0].text = str(qty)
from docx import Document from docx.shared import Inches doc = Document() doc.add_heading('Document', 0) p = doc.add_paragraph('Some text') p.add_run(' bold text ').bold = True p.add_run(' italic text ').italic = True doc.save('sample.docx')
def Write2Word(file_path, headline): document = Document() # 段落集合 document.paragraphs # 表格集合 document.tables # 节集合 document.sections # 样式集合 document.styles # 内置图形 document.inline_shapes document.add_heading(u'MS WORD写入测试', 0) 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.font.color.rgb = RGBColor(0x0, 0xff, 0x0) # 绿色 #设置斜体 run = paragraph.add_run(u'斜体、') run.italic = True #设置粗体 run = paragraph.add_run(u'粗体') run.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,请自行添加脚本所在目录中) img_name = "F:/python-libs/trunk/image/combine_image/need_combine_images/test1.jpg" document.add_picture(img_name, width=Inches(1.25)) #增加表格 table = document.add_table(rows=1, cols=3) # 新增表格的行,列 # table.add_row() # table.add_column(20) # 必须声明width,否则报错 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 range(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() #添加255个圆圈到word p = document.add_paragraph() r = p.add_run() img_size = 20 for x in range(255): im = Image.new("RGB", (img_size, img_size), "white") draw_obj = ImageDraw.Draw(im) draw_obj.ellipse((0, 0, img_size - 1, img_size - 1), fill=255 - x) # 画圆 fake_buf_file = BytesIO() # 用BytesIO将图片保存在内存中,减少磁盘操作 im.save(fake_buf_file, "png") r.add_picture(fake_buf_file) # 插入图片 fake_buf_file.close() # 定义标题,再添加内容 # p_total = document.add_heading() # r_total = p_total.add_run("执行结果如下:") # r_total.font.bold = True # 字体加粗 # # 添加表格 # table = document.add_table(rows=1, cols=3, style="Light List Accent 5") # hdr_cells = table.rows[0].cells # hdr_cells[0].text = 'testName' # hdr_cells[1].text = 'param' # hdr_cells[2].text = 'exc' #添加二级标题 # p_total = document.add_heading("", 2) # r_total = p_total.add_run("this is second headline") # r_total.font.bold = True # 添加图片 # img_name = "F:/python-libs/trunk/image/combine_image/need_combine_images/test1.jpg" # document.add_picture(img_name, width=Inches(1.5)) # 插入有序表 document.add_paragraph('time') # 增加一个paragraph # #插入有序列表,段落的前面会有序号123 # document.add_paragraph('把冰箱门打开',style='List Number') # document.add_paragraph('把大象装进去',style='List Number') # document.add_paragraph('把冰箱门关上',style='List Number') # #插入无序列表,段落的前面没有序号 # document.add_paragraph('把冰箱门打开',style='List Bullet') # document.add_paragraph('把大象装进去',style='List Bullet') # document.add_paragraph('把冰箱门关上',style='List Bullet') # 插入一个6行6列的表格 # table=document.add_table(rows=6,cols=6,style='Table Grid') # for i in range(0,6): # for j in range(0,6): # table.cell(i,j).text="第{i}行{j}列".format(i=i+1,j=j+1) document.save(file_path) # 保存文档
import requests import re import bs4 from docx import Document doc = Document() header = doc.add_heading('Python Language', 0).add_run().bold = True h1 = doc.add_table(rows=1, cols=2) h1.style = 'Table Grid' fields = h1.rows[0].cells fields[0].text = 'Content' fields[1].text = 'Url Content' a = requests.get('https://en.wikipedia.org/wiki/Python_(programming_language)') b = bs4.BeautifulSoup(a.text, 'html.parser') #c = b.find_all('a') d = re.compile('^tocsection-') e = b.find_all('li', attrs={'class': d}) prefix = 'https://en.wikipedia.org/wiki/Python_(programming_language)' content = [] for j in e: link = prefix + j.find('a')['href'] content.append(link) for g, i in zip(e, content): fields = h1.add_row().cells d = fields[0].add_paragraph(0).add_run(g.getText().split('\n')[0]) if g['class'][0] == 'toclevel-1': d.bold = True fields[1].text = str(i)
def write_mdt_outcome_template(report): """ :param pk: GEL Interpretationreport instance :return: Writes a docx template file for summarising proband MDT outcomes """ document = Document() document.add_picture(os.path.join(settings.STATIC_DIR, 'nhs_image.png')) header_image = document.paragraphs[-1] header_image.alignment = WD_ALIGN_PARAGRAPH.RIGHT document.add_heading('Genomics MDM record', 0) table = document.add_table(rows=1, cols=1, style='Table Grid') table.rows[0].cells[0].paragraphs[ 0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER run = table.rows[0].cells[0].paragraphs[0].add_run( 'THIS IS NOT A DIAGNOSTIC REPORT. UNVALIDATED FINDINGS SHOULD NOT BE USED TO INFORM CLINICAL ' 'MANAGEMENT DECISIONS.\n') run.font.color.rgb = RGBColor(255, 0, 0) run = table.rows[0].cells[0].paragraphs[0].add_run( 'This is a record of unvalidated variants identified through the 100,000 genome project. ' 'Class 3 variants are of uncertain clinical significance, future review and diagnostic confirmation ' 'may be appropriate if further evidence becomes available.\n') run.font.color.rgb = RGBColor(255, 0, 0) table.rows[0].cells[0].paragraphs[0].paragraph_format.space_before = Cm( 0.3) # table.rows[0].cells[0].paragraphs[0].paragraph_format.space_after = Cm(0.1) paragraph = document.add_paragraph() paragraph.add_run() table = document.add_table(rows=2, cols=4, style='Table Grid') heading_cells = table.rows[0].cells heading_cells[0].paragraphs[0].add_run('Patient Name').bold = True heading_cells[1].paragraphs[0].add_run('DOB').bold = True heading_cells[2].paragraphs[0].add_run('NHS number').bold = True heading_cells[3].paragraphs[0].add_run('Local ID').bold = True row = table.rows[1].cells row[0].text = str(report.ir_family.participant_family.proband.forename) \ + ' ' \ + str(report.ir_family.participant_family.proband.surname) row[1].text = str( report.ir_family.participant_family.proband.date_of_birth.date()) try: row[2].text = report.ir_family.participant_family.proband.nhs_number except TypeError: row[2].text = '' if report.ir_family.participant_family.proband.local_id: row[3].text = report.ir_family.participant_family.proband.local_id paragraph = document.add_paragraph() paragraph.add_run() paragraph.add_run('Referring Clinician: ').bold = True paragraph.add_run('{}\n'.format( report.ir_family.participant_family.clinician)) paragraph.add_run('Department/Hospital: ').bold = True paragraph.add_run('{}\n'.format( report.ir_family.participant_family.proband.gmc)) paragraph.add_run('Study: ').bold = True paragraph.add_run('100,000 genomes (whole genome sequencing)\n') paragraph.add_run('OPA ID: ').bold = True paragraph.add_run('{}\n'.format(report.ir_family.ir_family_id)) paragraph.add_run('Family ID: ').bold = True paragraph.add_run('{}\n'.format( report.ir_family.participant_family.gel_family_id)) paragraph.add_run('Genome Build: ').bold = True paragraph.add_run('{}\n\n'.format(report.assembly)) # paragraph.add_run('Phenotype summary: ').bold=True # if sample_info.hpo_terms: # paragraph.add_run('{}\n'.format(', '.join(list(json.loads(sample_info.hpo_terms))))) proband_variants = list( ProbandVariant.objects.filter(interpretation_report=report)) run = paragraph.add_run('MDT:\n') run.font.size = Pt(16) run.underline = True run.bold = True if proband_variants: run = paragraph.add_run('Variant Outcome Summary:\n') run.font.size = Pt(13) run.underline = True run.bold = True table = document.add_table(rows=1, cols=7, style='Table Grid') heading_cells = table.rows[0].cells run = heading_cells[0].paragraphs[0].add_run('Gene') run.bold = True run.font.size = Pt(9) run = heading_cells[1].paragraphs[0].add_run('HGVSg') run.bold = True run.font.size = Pt(9) run = heading_cells[2].paragraphs[0].add_run('HGVSc') run.bold = True run.font.size = Pt(9) run = heading_cells[3].paragraphs[0].add_run('HGVSp') run.bold = True run.font.size = Pt(9) run = heading_cells[4].paragraphs[0].add_run('Zygosity') run.bold = True run.font.size = Pt(9) run = heading_cells[5].paragraphs[0].add_run('Phenotype Contribution') run.bold = True run.font.size = Pt(9) run = heading_cells[6].paragraphs[0].add_run('Class') run.bold = True run.font.size = Pt(9) for proband_variant in proband_variants: cells = table.add_row().cells transcript = proband_variant.get_transcript() transcript_variant = proband_variant.get_transcript_variant() if transcript is None or transcript_variant is None: raise ValueError( f"Please select transcripts for all variants before exporting\n" ) rdr = proband_variant.create_rare_disease_report() run = cells[0].paragraphs[0].add_run(str(transcript.gene)) run.font.size = Pt(7) run = cells[1].paragraphs[0].add_run(str(transcript_variant.hgvs_g)) run.font.size = Pt(7) run = cells[2].paragraphs[0].add_run(str(transcript_variant.hgvs_c)) run.font.size = Pt(7) run = cells[3].paragraphs[0].add_run(str(transcript_variant.hgvs_p)) run.font.size = Pt(7) run = cells[4].paragraphs[0].add_run(str(proband_variant.zygosity)) run.font.size = Pt(7) run = cells[5].paragraphs[0].add_run( str(rdr.get_contribution_to_phenotype_display())) run.font.size = Pt(7) run = cells[6].paragraphs[0].add_run(str(rdr.classification)) run.font.size = Pt(7) mdt_linkage_list = MDTReport.objects.filter( interpretation_report=report).values('MDT') mdt = MDT.objects.filter( id__in=mdt_linkage_list).order_by('-date_of_mdt').first() paragraph = document.add_paragraph() paragraph.add_run('MDT Date: ').bold = True paragraph.add_run('{}\n'.format(mdt.date_of_mdt.date())) paragraph.add_run('MDT Attendees: ').bold = True clinicians = Clinician.objects.filter(mdt=mdt.id).values_list('name', flat=True) clinical_scientists = ClinicalScientist.objects.filter( mdt=mdt.id).values_list('name', flat=True) other_staff = OtherStaff.objects.filter(mdt=mdt.id).values_list('name', flat=True) attendees = list(clinicians) + list(clinical_scientists) + list( other_staff) paragraph.add_run('{}\n\n'.format(', '.join(attendees))) paragraph.add_run() run = paragraph.add_run('Discussion:\n') run.font.size = Pt(13) run.underline = True run.bold = True paragraph.add_run('{}\n\n'.format( report.ir_family.participant_family.proband.discussion.rstrip())) run = paragraph.add_run('Action:\n') run.font.size = Pt(13) run.underline = True run.bold = True paragraph.add_run('{}\n'.format( report.ir_family.participant_family.proband.action.rstrip())) return document, mdt
from docx import Document # from docx.shared import Inches document = Document() document.add_heading('<<JMF_CLIENTNAME>>', 0) p = document.add_paragraph('<<jmf_DateCreated>>') # p.add_run('bold').bold = True # p.add_run(' and some ') # p.add_run('italic.').italic = True document.add_heading('<<+DECINTRO+Introduction - Declaration>>', level=1) document.add_paragraph('Intense quote', style='Intense Quote') # document.add_paragraph( # 'first item in unordered list', style='List Bullet' # ) # document.add_paragraph( # 'first item in ordered list', style='List Number' # ) # document.add_picture('JLTIndiaChallenge.png', width=Inches(1.25)) # records = ( # (3, '101', 'Spam'), # (7, '422', 'Eggs'), # (4, '631', 'Spam, spam, eggs, and spam') # ) # # table = document.add_table(rows=1, cols=3) # hdr_cells = table.rows[0].cells
class ListDocCandidatePresentation(APIView): from django.http import HttpResponse from io import BytesIO employee = None candidate_presentation = None permission_classes = (permissions.AllowAny, ) def get(self, request, model_id): from docx import Document try: self.employee = Employee.objects.get(id=model_id) self.candidate_presentation = Document() self.candidate_presentation.add_heading('Candidate Presentation', 0) self._generate_employee_summary() if self.employee.position is not None and self.employee.career_start_date is not None: self._generate_employee_summary_of_qualification() self._generate_technical_summary() self._generate_professional_experience() return self._generate_file_response() except ObjectDoesNotExist as e: return Utils.error_response(e.args, status.HTTP_404_NOT_FOUND) def _generate_employee_summary(self): from docx.shared import Inches paragraph = self.candidate_presentation.add_paragraph() paragraph.left_indent = Inches(5) try: photo = self.candidate_presentation.add_picture( self.employee.image.file, width=Inches(1)) except Exception as e: from pman.settings import MEDIA_ROOT photo = self.candidate_presentation.add_picture( MEDIA_ROOT + '/profile_images/missing.png', width=Inches(1)) name = self.candidate_presentation.add_paragraph('Name: ') run = name.add_run(self.employee.get_full_name()) run.bold = True position = self.candidate_presentation.add_paragraph( 'Position: {0}'.format(self.employee.position)) description = self.candidate_presentation.add_paragraph( self.employee.description) def _generate_employee_summary_of_qualification(self): from datetime import date import math self.candidate_presentation.add_heading('Summary of qualification') experience = self.candidate_presentation.add_paragraph( '{0} years of experience as {1}'.format( math.ceil( (date.today() - self.employee.career_start_date).days / 365.0), self.employee.position)) def _generate_technical_summary(self): from itertools import groupby self.candidate_presentation.add_heading('Technical Summary') for key, skills in groupby( self.employee.skills.all().order_by('category_id'), lambda x: x.category): self.candidate_presentation.add_paragraph('{0}: {1}'.format( key.name, ', '.join([skill.name for skill in list(skills)]))) def _generate_professional_experience(self): self.candidate_presentation.add_heading('Professional Experience') for employee_project in self.employee.employeeproject_set.all(): self._generate_employee_project(employee_project) def _generate_employee_project(self, employee_project): project_name = self.candidate_presentation.add_paragraph() run = project_name.add_run(employee_project.project_id.name) run.bold = True skills = self.candidate_presentation.add_paragraph( 'Technologies: {0}'.format(', '.join( [skill.name for skill in employee_project.skills.all()]))) project_description = self.candidate_presentation.add_paragraph( employee_project.project_id.description) employee_description = self.candidate_presentation.add_paragraph( employee_project.description) def _generate_file_response(self): f = self.BytesIO() self.candidate_presentation.save(f) length = f.tell() f.seek(0) response = self.HttpResponse( f.getvalue(), content_type= 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ) response[ 'Content-Disposition'] = 'attachment; filename={0}.docx'.format( self.employee.get_full_name()) response['Content-Length'] = length return response
from docx import Document #python-docx을 이용하기 위해 사용한다. 워드 문서 파일 만들때 사용 document = Document() #만들어둔 파일을 Document('여기!')에 추가를 해서 넣을 수 있습니다. 해당하는 양식이 있거나 이 이후에 추가를 해야 한다면 저 부분에 파일의 이름을 넣으면 됩니다. #만들어둔 스타일이 있기때문에 해당하는 내용은 지워도 상관 없습니다. document.add_heading('파이썬으로 워드파일 만들기', 0) #제목 추가 document.add_heading('첫번째로 만들어 보는 워드파일', 1) # 0과1의 차이는 제목들의 우선순위를 나타내는 것 같다. # 같이 첨부된 파일을 보면 알 수 있다. document.add_heading('python-docx로 만들 수 있다.', 2) document.add_paragraph('이 부분은 본문에 해당한다.') #word파일 같은 경우는 자신이 스타일을 지정하거나 하는 방법으로 스타일을 저장해 둘 수가 있다. 예를들어 문단 앞에 동그라미 기호 표시를 스타일로 지정을 하고 #document.add_paragraph('이 부분은 본문에 해당한다.', style='지정한 해당 스타일 이름') -> 이런식으로 추가를 하면 해당 style로 설정이 된다. #아래의 표도 style을 미리 지정을 하고, 불러오게 되면 설정이됩니다. table = document.add_table(rows=1, cols=3) #table.style = '지정한 해당 스타일 이름' -> 다음과 같습니다. hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Qty' hdr_cells[1].text = 'Id' hdr_cells[2].text = 'Desc' row_cells = table.add_row().cells row_cells[0].text = str(123) row_cells[1].text = str(456) row_cells[2].text = '아무글씨' #table을 만드는 양식이다. rows는 1행 cols는 3열 document.save('demo.docx') #docx파일을 생성한다. #해당하는 예시는 구글에 python-docx를 검색해서 첫번째 브라우저에 들어가면 나옵니다.
""" from docx import Document from docx.enum.text import WD_PARAGRAPH_ALIGNMENT from docx.oxml.ns import qn from docx.shared import RGBColor, Pt from docx.shared import Inches, RGBColor from lzStr import lzStr # todo 初始化一个文档 document = Document() # 全局指定字体 document.styles['Normal'].font.name = u'.萍方-简' document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'.萍方-简') # todo 加个标题 paragraph = document.add_heading('离职申请', level=3) # todo 居中 paragraph_format = paragraph.paragraph_format paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER paragraph = document.add_paragraph() paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER run = paragraph.add_run("") run.add_picture('./image.jpg', width=Inches(1.0), height=Inches(1.0)) paragraph = document.add_paragraph() lz_add_run = paragraph.add_run(lzStr.format(name="吴老板")) lz_add_run.font.size = Pt(8) # 字体大小设置,和word里面的字号相对应 lz_add_run.font.color.rgb = RGBColor(54, 95, 145)
def readingFile(path1, path2, mode): totalCompare = 0 errorCompare = 0 # using docx module document = Document() #opening the file fil = open(path1, "r+") fil1 = open(path2, "r+") #calculating the number of lines in the files countfil = 0 countfil1 = 0 print("calculating the length of file 1 : ") for i in fil: countfil += 1 customClearScreen() print("calculating the length of file 2 : ") for i in fil1: countfil1 += 1 count = 1 # calculating the length when the two files will be zipped for running for loop if (countfil > countfil1): totalCompare = countfil fromLen = countfil1 else: totalCompare = countfil1 fromLen = countfil # closing and reopening file - as their is some error ocurring if we dont do this - the zipped for loop was not running fil.close() fil1.close() customClearScreen() print("starting to compare : ") fil = open(path1, "r+") fil1 = open(path2, "r+") # running the for loop as both files zipped so that we can get the lines from both files at the same time for i, j in zip(fil, fil1): print("on line {} outOf {}".format(count, fromLen)) # getting the lines string1 = i.strip() string2 = j.strip() # if the mode is 1 converting both the captuared lines to lower case to remove case sensitivity if (mode == 1): string1 = string1.lower() string2 = string2.lower() else: pass # getting the individual words in the lines captured in string 1 and sting 2 - so that we can output the colored words which do not match myList1 = list(string1.split()) myList2 = list(string2.split()) myList1Len = len(myList1) myList2Len = len(myList2) # making the list of same length - inserting " " in the list which has less elements - to avoid any kind of error like while running for loop we may get a[i] - their can be nothing at i position - to remove this error we are doing this if (myList1Len == myList2Len): pass else: if (myList1Len > myList2Len): elementsToBeInserted = myList1Len - myList2Len for i in range(elementsToBeInserted): myList2.append(" ") else: elementsToBeInserted = myList2Len - myList1Len for i in range(elementsToBeInserted): myList1.append(" ") # now since both list are of same length and also have same elements so if list1 == list2 - then the string1 will be equal to string2 if (myList1 == myList2): pass # if the list is not same then looping over each element of both list and comparing individual elements else: # using docx stringHeading = "Error on line " + str(count) + " : " document.add_heading(stringHeading, level=1) p = document.add_paragraph(style='List Bullet') # starting to loop through each element on both list at the same time - as the both list are of same length so index will return same position element from both list # looping over for printing the data of the line in txt1 for index in range(len(myList1)): i = myList1[index] j = myList2[index] stringToadd = str(i) + " " # if the elements match then the output will be in black colour if (i == j): p.add_run(stringToadd) #if donot match then the word will be outputed in red colour else: errorCompare = errorCompare + 1 run = p.add_run(stringToadd) run.font.color.rgb = RGBColor(0xff, 0x00, 0x00) p = document.add_paragraph(style='List Bullet') # looping over again to print the data of line in txt2 for index in range(len(myList1)): i = myList1[index] j = myList2[index] stringToadd = str(j) + " " if (i == j): p.add_run(stringToadd) else: errorCompare = errorCompare + 1 run = p.add_run(stringToadd) run.font.color.rgb = RGBColor(0xff, 0x00, 0x00) # increasing the count to keep tarck were we have reached count += 1 errorCompare = errorCompare / 2 trackCount = count - 1 count = 0 # again closing and opening the file to avoid errors fil.close() fil1.close() customClearScreen() print("outputting extra lines founded : ") fil = open(path1, "r+") fil1 = open(path2, "r+") # if the txt1 has more lines than txt2 if (countfil > countfil1): stringHeading = "these are the extra lines after the " + str( countfil1) + " in txt file no1 : " document.add_heading(stringHeading, level=1) p = document.add_paragraph() # looping to get the elements in txt1 for i in fil: # will start printing after the length till we have compared - as we used zip above - we compare only till the length of the smaller txt file if (trackCount <= count): string1 = i.strip() p.add_run(string1) p.add_run("\n") errorCompare = errorCompare + 1 count += 1 # if the txt2 has more lines than txt2 elif (countfil < countfil1): stringHeading = "these are the extra lines after the " + str( countfil) + " in txt file no2 : " document.add_heading(stringHeading, level=1) p = document.add_paragraph() for i in fil1: if (trackCount <= count): string1 = i.strip() p.add_run(string1) p.add_run("\n") errorCompare = errorCompare + 1 count += 1 # using docx and finally outputting the data document.save('output_result.docx') fil.close() fil1.close() percentageMatched = 100 - ((errorCompare / totalCompare) * 100) return percentageMatched
# pip install python-docx from docx import Document from docx.shared import Inches document = Document() document.add_heading('Bảng điểm', 0) # level=0: Title document.add_paragraph('Họ tên: Trần Anh', style='Heading 3') document.add_paragraph('Python', style='List Bullet') document.add_paragraph('SQL', style='List Bullet') document.add_paragraph('Visualization', style='List Bullet') document.add_paragraph('HTML5', style='List Number') document.add_paragraph('CSS3', style='List Number') document.add_heading('Chi tiết', level=1) records = [ { "tenmon" : "Toán", "diem": 9, "sotc": 3 }, { "tenmon" : "Anh văn", "diem": 7, "sotc": 3 }, ] table = document.add_table(rows=1, cols=3) hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Tên môn' hdr_cells[1].text = 'Số tín chỉ' hdr_cells[2].text = 'Điểm' for mon in records: row_cells = table.add_row().cells row_cells[0].text = mon["tenmon"] row_cells[1].text = str(mon["sotc"]) row_cells[2].text = str(mon["diem"])
from docx import Document from docx.shared import Inches import requests ########################################### # First Page ########################################### # constants IMAGE_AUTHOR = "Image Author: Tai's Captures" TACO_API_URL = "https://taco-1150.herokuapp.com/random/?full_taco=true" STUDENT_NAME = "Student Name: DQ" document = Document() # object created document.add_heading('Random Taco Cookbook', 0) # add heading document.add_picture('taco_original_thumbnail.jpg', width=Inches(6.67)) # add picture document.add_paragraph(IMAGE_AUTHOR) # add text document.add_paragraph(TACO_API_URL) # add text document.add_paragraph(STUDENT_NAME) # add text ########################################### # Recipes ########################################### # fetchJSON # get JSON response # params: # url:takes taco api url # return:
all_interoperability.append(as_list) length = len(all_interoperability) as_doc = Document() style = as_doc.styles['Normal'] font = style.font font.name = 'Calibri' title = 'All responses mentioning "interoperability" (DSA consultation) - ' title += user_type title += ' (n='+str(length)+')' as_doc.add_heading(title, 0) interop_questions = [] for element in all_interoperability: new_questions = [q_a[0] for q_a in element[3:]] interop_questions.extend(new_questions) reference, organisation_name, country = element[0:3] heading_2 = reference[1] heading_2 += ' - '+organisation_name[1] heading_2 += ' ('+country[1]+')' as_doc.add_heading(heading_2, level=2) for question, content in element[3:]:
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/51.0.2704.63 Safari/537.36' }).text music_code = re.findall(r'<ul class="f-hide">.*?</a></li></ul>', music_text, re.I)[0] musicUrls = re.findall(r'<li><a href="(.*?)">', music_code) musicNames = re.findall(r'>(.*?)</a></li><li><a href="/song\?id=', music_code) image_url = re.findall(r'"images": \["(.*?)"\],', music_text) image_f = open((Id + '.jpg'), 'wb') request = urllib.request.urlopen(image_url[0]) image = request.read() image_f.write(image) image_f.close() listNum = 1 document = Document() document.add_heading('Music List', 0) document.add_paragraph('This is the playlist you want:\n') document.add_picture((Id + '.jpg'), width=Inches(2.25)) for musicUrl, musicName in zip(musicUrls, musicNames): music_Url = "https://music.163.com/#" + musicUrl if listNum != 1: words = str(listNum - 1) + ') ' + '[' + musicName + ']' + ' Url : ' + music_Url document.add_paragraph(words) listNum += 1 document.add_page_break() document.save('Id' + Id + '.docx')
from docx import Document from docx.shared import Inches 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:
from docx import Document from docx.shared import Pt from docx.oxml.ns import qn from docx.shared import Inches #如果程序文件名字是 docx.py,程序又 from docx import Document 的话,就会出现ImportError: cannot import name 'Document'错误。 #创建对象 document = Document() #加入不同等级的标题 document.add_heading('面向API编程:使用python编辑word文档', 0) document.add_heading(u'二级标题 人生苦短,我用python.', 1) document.add_heading(u'二级标题 这个系列主要学习记录使用python实现办公自动化。', 2) #添加文本 paragraph = document.add_paragraph(u'添加了文本 那么就从最常见的办公三件套 -----word开始。') #设置字号 run = paragraph.add_run(u'设置字号') run.font.size = Pt(36) #设置字体 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'斜体、')
def processRow(pos): list1 = app.getTableRow("SmellTable", pos) var = list1[0] c = conn.cursor() c.execute("SELECT * FROM smell WHERE smell = ?", [var]) row = c.fetchone() smell = row[0] description = row[1] rationale = row[2] causes = row[3] exDesc = row[4] png = row[5] affected = row[7] abstractions = row[8] considerations = row[9] #Description document = Document() document.add_heading(smell.title(), 0) now = datetime.datetime.now() dt = now.strftime("%Y-%m-%d %H:%M") p = document.add_paragraph() run = p.add_run('Generated Automatically on ' + dt).italic = True p = document.add_paragraph() run = p.add_run('Description: ') run.bold = True run.underline = True font = run.font font.size = Pt(12) p = document.add_paragraph(description) paragraph_format = p.paragraph_format paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY #Rationale p = document.add_paragraph() run = p.add_run('Rationale: ') run.bold = True run.underline = True font = run.font font.size = Pt(12) p = document.add_paragraph(rationale) paragraph_format = p.paragraph_format paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY #Causes p = document.add_paragraph() run = p.add_run('Potential Causes: ') run.bold = True run.underline = True font = run.font font.size = Pt(12) p = document.add_paragraph(causes) paragraph_format = p.paragraph_format paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY #Example and Figure p = document.add_paragraph() run = p.add_run('Examples: ') run.bold = True run.underline = True font = run.font font.size = Pt(12) p = document.add_paragraph(exDesc) paragraph_format = p.paragraph_format paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY if png != '': if not os.path.exists(smell): os.makedirs(smell) filename = smell + '/' + smell + '.png' with open(filename, 'wb') as output_file: output_file.write(png) document.add_picture(filename) else: if not os.path.exists(smell): os.makedirs(smell) #Affected p = document.add_paragraph() run = p.add_run('Imptacted Quality Attributes: ') run.bold = True run.underline = True font = run.font font.size = Pt(12) p = document.add_paragraph(affected) paragraph_format = p.paragraph_format paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY #Abstractions p = document.add_paragraph() run = p.add_run('Affected Architectural Abstractions: ') run.bold = True run.underline = True font = run.font font.size = Pt(12) p = document.add_paragraph(abstractions) paragraph_format = p.paragraph_format paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY #Practical Considerations p = document.add_paragraph() run = p.add_run('Practical Considerations: ') run.bold = True run.underline = True font = run.font font.size = Pt(12) p = document.add_paragraph(considerations) paragraph_format = p.paragraph_format paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY document.add_page_break() document.save(smell + '/' + smell + '.docx') app.infoBox("MsgWord", "A document has been generated successfully!", parent=None)
from docx import Document from docx.shared import Inches # 创建word文档对象 document1 = Document() document = Document("择天1.docx") # 添加标题 document1.add_heading('择天记', 0) # 前一行 lastLine = '' count = 0 nextLine = '' readNextLine = False all_paragraphs = document.paragraphs for paragraph in all_paragraphs: line = paragraph.text if line in '\n' \ or '.com' in line \ or 'http:' in line \ or '----' in line: continue # document1.add_paragraph(paragraph.text) if readNextLine == True: nextLine = line readNextLine = False continue
def add_row(data): row_new = table.add_row() ll = data.split() print(ll) i = 0 for cell in row_new.cells: cell.text = ll[i] #print(ll[i]) #cell.text = re.match(r'(.+)e-(\d+)',ll[i]).group(1) i += 1 if __name__ == '__main__': doc = Document() doc.add_heading('power analysis', 0) table = doc.add_table(rows=1, cols=5, style="Table Grid") header = table.rows[0].cells header[0].text = 'Heir' header[1].text = 'Internal (mW)' header[2].text = 'Switch (mW)' header[3].text = 'Leak (mW)' header[4].text = 'Total (mW)' try: if sys.argv[1] == 'pka_log': read_f = open("pka_result.log", 'w') mod_f = open("pkamodules.txt", 'r') elif sys.argv[1] == 'spacc_log': read_f = open("spacc_result.log", 'w') mod_f = open("spacc_modules.txt", 'r')
def create(employee_name, designation, date, base_income, pera, deductions, deduction_total): # employee_name = 'Jasper Nichol M. Fabella' # designation = 'Programmer III' # date = 'October 1-15 2019' # base_income = 9000 # pera = 1000 gross_income = base_income + pera # # deductions = [ # ['PHILHEALTH',1000] # ] if os.path.exists("{}".format('payslip.docx')): os.remove("{}".format('payslip.docx')) document = Document() document.add_heading('PHRMO SALARY SLIP FOR {}'.format(date), 1) # p = document.add_paragraph('\nSTAFF NAME: ') # p.add_run('{}'.format(employee_name)).bold = True # p.add_run('\nDESIGNATION: ') # p.add_run('{}'.format(designation)).bold = True # p.add_run('\nDATE: ') # p.add_run('{}'.format(date)).bold = True # p.add_run(' and some ') # p.add_run('italic.').italic = True employee_details = (('STAFF NAME:', employee_name), ('DESIGNATION:', designation), ('DATE:', date)) table = document.add_table(rows=1, cols=2) for qty, id in employee_details: row_cells = table.add_row().cells row_cells[0].text = str(qty) #row_cells[0].paragraphs[0].runs[0].font.bold = True row_cells[1].text = id row_cells[1].paragraphs[0].runs[0].font.bold = True p = document.add_paragraph('', style='Intense Quote') p = document.add_paragraph('BASE SALARY: ') p.add_run('{:,.2f}'.format(base_income)).bold = True p.add_run('\nPERA: ') p.add_run('{:,.2f}'.format(pera)).bold = True p.add_run('\nGROSS INCOME: ') p.add_run('{:,.2f}'.format(gross_income)).bold = True p = document.add_paragraph('', style='Intense Quote') p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER p.add_run('This is a computer generated slip no signature required' ).font.size = Pt(8) #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[1].text = 'DEDUCTIONS' hdr_cells[1].paragraphs[0].runs[0].font.bold for qty, id in deductions: row_cells = table.add_row().cells row_cells[1].text = str(qty) row_cells[2].text = '{:,.2f}'.format(id) p = document.add_paragraph('', style='Intense Quote') p = document.add_paragraph() p = document.add_paragraph('NET INCOME: ') p.add_run('{:,.2f}'.format(gross_income - deduction_total)).bold = True document.save('payslip.docx') os.system('start payslip.docx')
def make_mou(filename, data): """MOU 문서 생성. MOU 문서를 생성한다. 이 때 필요한 데이터(data)와 파일이름을 받는다. 주의: 기존에 filename과 동일한 파일이 이미 존재를 하면 기존 파일이 생성되고 새로운 파일로 대체된다. """ # 문서 생성 document = Document() # 제목 추가 p = document.add_heading('MOU(양해각서)', level=1) # 제목을 중앙정렬로 p.alignment = WD_ALIGN_PARAGRAPH.CENTER text = "(주) {company1_name}와 (주){company2_name} 의 업무제휴에 관한 양해각서".format( **data) p = document.add_paragraph() p.add_run(text).bold = True text = "㈜ (이하 ‘갑’이라 함)과 ㈜ (이하 ‘을’이라 함)은 당사자간의 " \ "우호협력관계를 확인하고 상호신뢰를 바탕으로 제휴에 따른 각자의 " \ "책임을 인식하며, 인터넷 사업 분야에 있어 교류와 협력이 당사자간의 "\ "상호 이해증진에 기여할 것임을 확신하면서, 다음과 같이 합의한다." p = document.add_paragraph(text) text = "제1조 목 적" p = document.add_paragraph(text, style="Heading 2") text = "본 계약은 ‘갑’과 ‘을’의 업무상 상호 공동이익의 증진을 도모함에 그 목적이 있다." p = document.add_paragraph(text) text = "제2조 협력내용" p = document.add_paragraph(text, style="Heading 2") text = "본 양해각서에 의한 제휴협력관계의 내용은 다음과 같다." p = document.add_paragraph(text) for cond in data["conditions"]: text = " " + cond p = document.add_paragraph(text) text = "제3조 분쟁해결" p = document.add_paragraph(text, style="Heading 2") text = "본 양해각서의 해석이나 적용에 관한 분쟁은 당사자 간의 상호협력에 의하여 우호적으로 해결하며, 제3자의 개입을 허용하지 않는다." p = document.add_paragraph(text) text = "제4조 의무사항" p = document.add_paragraph(text, style="Heading 2") text = '1)"갑" 과 "을"은 제휴업무를 수행함에 있어서 선량한 관리자로서의 주의를 다하여야 한다.' p = document.add_paragraph(text) text = '2) "갑" 과 "을"은 본 계약의 내용을 신의에 따라 성실하게 이행한다.' p = document.add_paragraph(text) text = "제5조 기밀유지" p = document.add_paragraph(text, style="Heading 2") text = '"갑" 과 "을"은 업무제휴를 통하여 취득한 정보 등을 상대방의 동의 없이 상호간의 공동 사업 추진 외의 목적에 사용하거나 외부에 누출 및 누설하여서는 아니되며, 계약 종료 이후에도 같다.' p = document.add_paragraph(text) text = "제6조 제반 업무 연락" p = document.add_paragraph(text, style="Heading 2") text = "본 협정과 관련된 제반 업무 연락은 문서로 함을 원칙으로 한다. 이 경우 문서는 인편 및 우편 그리고 팩스로 전달함으로써 정당하게 이루어진 것으로 한다. " p = document.add_paragraph(text) text = "제7조 계약의 해지" p = document.add_paragraph(text, style="Heading 2") text = "본 협약은 서명일로부터 구체적인 본 계약을 체결하기 전까지 유효하다." p = document.add_paragraph(text) text = "제8조 유효기간" p = document.add_paragraph(text, style="Heading 2") text = "본 협약은 서명일로부터 구체적인 본 계약을 체결하기 전까지 유효하다." p = document.add_paragraph(text) text = "제9조 법적구속력" p = document.add_paragraph(text, style="Heading 2") text = "본 업무협약은 양사의 상호 업무에 관한 협력사항을 열거한 것으로, 제5조를 제외하고는 법적 구속력을 갖지 않는다." p = document.add_paragraph(text) text = "제10조 기타사항" p = document.add_paragraph(text, style="Heading 2") text = "본 계약서상에 명시되지 않은 기타 사항은 별도 협의 하에 처리한다. 본 양해각서는 {year}년 {month}월 {day}일 2부를 작성, 날인되었으며, 이 모두는 동등한 효력을 지닌다.".format( **data) p = document.add_paragraph(text) # 공백 추가 p = document.add_paragraph("\n\n\n") table = document.add_table(rows=2, cols=2) cells = table.rows[0].cells cells[0].text = '갑: ㈜ {company1_name}'.format(**data) cells[1].text = '갑: ㈜ {company2_name}'.format(**data) cells = table.rows[1].cells cells[0].text = '대표이사 {company1_ceo}'.format(**data) cells[1].text = '대표이사 {company2_ceo}'.format(**data) update_style(document) # 문서 저장 document.save(filename)
from docx import Document from docx.shared import Inches document = Document() document.add_heading('Word Documentation Automation', 0) p = document.add_paragraph('A script for SDD documentation ') 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='Intense Quote') document.add_paragraph( 'first item in unordered list', style='List Bullet' ) document.add_paragraph( 'first item in ordered list', style='List Number' ) records = ( (1, '26', 'Sharath'), (2, '25', 'Bharath'), (3, '24', 'Bhavya') ) table = document.add_table(rows=1, cols=3) hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Id'
def generarInforme (str_agenda = "agenda.json"): # Abrir el fichero con la agenda y extraer datos en formato json with open (str_agenda) as json_file: json_agenda = json.load(json_file) json_file.close() # Obtener fechas de la agenda y ordenar ascendentemente list_indices = sorted(list(json_agenda)) doc = Document() # Crear documento vacío doc.add_heading('Informe de alergia \n' + decodificarFecha(list_indices[0]) + ' --- ' + decodificarFecha(list_indices[-1]), 0) # Añadir registros al documento for str_fecha in list_indices: # Título de la entrada, fecha doc.add_heading(decodificarFecha(str_fecha), 1) # Sintomatología try: str_sintomas = str(json_agenda[str_fecha]["sintomas"]) p = doc.add_paragraph() p.add_run("Síntomas: \n").bold = True p.add_run(str_sintomas).italic = True except Exception as e: pass # Medicación try: str_desayuno = str(json_agenda[str_fecha]["medicacion"]["desayuno"]) str_comida = str(json_agenda[str_fecha]["medicacion"]["comida"]) str_cena = str(json_agenda[str_fecha]["medicacion"]["cena"]) if ((str_desayuno + str_comida + str_cena) != ""): p = doc.add_paragraph() p.add_run("Medicación:").bold = True if (str_desayuno != ""): doc.add_paragraph("desayuno: " + str_desayuno, style="ListBullet") if (str_comida != ""): doc.add_paragraph("comida: " + str_comida, style="ListBullet") if (str_cena != ""): doc.add_paragraph("cena: " + str_cena, style="ListBullet") except Exception as e: pass # Estado de la papelera try: str_porcentaje = str(json_agenda[str_fecha]["papelera"]) if (str_porcentaje != "-1"): p = doc.add_paragraph() p.add_run("Papelera: ").bold = True p.add_run(str_porcentaje + "%") except Exception as e: pass # Valoración try: dic_valoracion = {"1": "Bueno", "2": "Regular", "3": "Malo"} str_valoracion = str(json_agenda[str_fecha]["valoracion"]) str_valoracion = dic_valoracion[str_valoracion] p = doc.add_paragraph() p.add_run("Valoración: ").bold = True p.add_run(str_valoracion) except Exception as e: pass #print(json_agenda[str_fecha]) # Grafica de papelera try: doc.add_paragraph() doc.add_picture('papelera.png', width=Inches(7)) except Exception as e: raise e # Guardar documento doc.save("informeAlergia.docx")
else: pass #phone_number speak("That's okay! Now I'd need you to enter your phone number?") phone_number = input('\nEnter phone number: ') #email speak('Please Enter your email') email = input('\nEnter email: ') namedetails = document.add_paragraph(f'{name}\n{phone_number}\n{email}') # about me document.add_heading('About me') speak("Okay it's going great! Now tell me about yourself like what jobs do you wish to apply for, etcetra") document.add_paragraph( input('\nTell about yourself: ') ) # work experience speak("Have you ever worked in a company before?") worked = input("\nHave you worked in a company before? (y/n) ") if worked == 'y': speak("Please enter details") document.add_heading('Work Experience') p = document.add_paragraph() company = input('\nEnter Company Name: ') from_date = input('From Date: ')
save('py_code.docx') @asyncio.coroutine def write_code(filename): doc.add_paragraph('源码文件-' + os.path.split(filename)[-1], style='List Number') tb = doc.add_table(rows=1, cols=1, style='Medium Shading 1 Accent 1') tb.rows[0].cells[0].text = '源码内容' with open(filename, 'rb') as code_file: code_text = code_file.read().decode() tb.add_row().cells[0].text = code_text p = doc.add_paragraph('\n') print('writing py', filename) def save(filename): doc.save(filename) if __name__ == '__main__': doc = Document() doc.add_heading('Python源码文档', level=0) loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait((list_py('../process_'), ))) loop.close()
document = Document() # Write a paragraph document.add_paragraph('Hello world!') paraObj1 = document.add_paragraph('This is a second paragraph.') paraObj2 = document.add_paragraph('This is a yet another paragraph.') # insert paragraph before paraObj1.insert_paragraph_before('Lorem ipsum') # add text to the end of an existing paragraph paraObj1.add_run(' This text is being added to the second paragraph.') # Add heading document.add_heading('This is Header 0', 0) document.add_heading('This is Header 1', 1) document.add_heading('This is Header 2', 2) document.add_heading('This is Header 3', 3) document.add_heading('This is Header 4', 4) # Applying bold and italic paragraph = document.add_paragraph() paragraph.add_run('Lorem ipsum ') paragraph.add_run('dolor').bold = True paragraph.add_run(' sit amet.') run = paragraph.add_run('Okay.') run.bold = True run.italic = True # Applying a character style
from docx import Document from docx.shared import Inches doc1 = Document() doc1.add_heading('Title1', level=1) doc1.add_heading('Title2', level=2) doc1.add_heading('Title3', level=3) doc1.add_page_break() table = doc1.add_table(rows=2, cols=2) 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!' for row in table.rows: for cell in row.cells: print(cell.text) row_count = len(table.rows) col_count = len(table.columns) row = table.add_row() table.style = 'LightShading-Accent1' doc1.add_heading('head1', level=3) #####
def income(self,event): name=self.t1.get() occup=self.t2.get() sal=self.t3.get() vyear=self.t5.get() document = Document() document.add_picture('project.png', width=Inches(0.8)) document.add_paragraph('GOVERNMENT OF MAHARASHTRA') h = document.add_heading('INCOME CERTIFICATE', 0) h.alignment = WD_ALIGN_PARAGRAPH.CENTER i = document.add_paragraph('THIS IS TO CERTIFY THAT ') i.alignment = WD_ALIGN_PARAGRAPH.CENTER p = document.add_paragraph() p.add_run({name}).bold = True p.alignment = WD_ALIGN_PARAGRAPH.CENTER q = document.add_paragraph('IS OCCUPIED AS ') q.add_run({occup}).bold = True q.alignment = WD_ALIGN_PARAGRAPH.CENTER r = document.add_paragraph('AND HAS AN ANNUAL INCOME OF ') r.add_run({sal}).bold = True r.alignment = WD_ALIGN_PARAGRAPH.CENTER s = document.add_paragraph('IN THE YEAR OF ') s.add_run({vyear}).bold = True s.alignment = WD_ALIGN_PARAGRAPH.CENTER document.add_paragraph() document.add_picture('stamp.jpg', width=Inches(0.8)) document.add_picture('sign.jpg', width=Inches(0.8)) document.add_paragraph('NAYAB TAHSILDAR') document.add_paragraph('MULUND') sj = self.uidai + "i.docx" document.save(sj) #SQL ACTIVITY db = pymysql.connect("localhost", "root", "root", "adv") cursor = db.cursor() sql = "UPDATE cia SET INCOME = 1 WHERE UIDAI={} ".format(self.uidai) try: cursor.execute(sql) db.commit() os.startfile(str(self.uidai) + "i.docx") os.startfile(str(self.uidai) + "i.docx", "print") exit(0) except pymysql.Error as e: print(e) #b = Income(root,'12345') #root.mainloop()
plt.ylabel(met) plt.xticks(rotation=90) fig = plt.gcf() fig.set_size_inches(12, 8) fig.savefig(out+met+'_box'+run+'.png', dpi=300) fig.clear() document.add_picture(out+met+'_box'+run+'.png', width=Inches(6.25)) return ob exp=input("Experiment Name: ") var=input("Type the variable of the Experiment: ") samples=input("and the samples variation separated by comma (e.g. 100,150,200,250,300):") document = Document() document.add_heading("Complete Report "+exp, 0) samples=samples.split(",") samples_int=[] if var!='Ecoli strains': for s in samples: samples_int.append(float(s)) else: samples_int=samples metrics={} outs=os.listdir("outputs_csv") out="outputs_csv/" colors=[] for each in outs: met=each.split(".")