def docfile(key): tpl = DocxTemplate( '/Users/xintongli/Documents/学习/Python/Interested Project/Construction Invoice/Invoice_template.docx' ) context = { 'parabill': '{}'.format(key), 'paraivnum': '{}'.format(key) + '{}'.format(today.strftime('%Y%m%d')), 'paradate': '{}'.format(today), 'paradue': '{}'.format(today + dt.timedelta(days=7)), 'paratotalpay': '{}'.format(df[key].iloc[-1, -1]) } table = tpl.add_table(rows=len(df[key].index) + 1, cols=(len(df[key].columns))) for j in range(len(header)): table.cell(0, j).text = header[j] for i in range(df[key].shape[0]): table.cell(i + 1, 0).text = str(df[key].index[i]) for i in range(df[key].shape[0]): for j in range(len(header) - 1): table.cell(i + 1, j + 1).text = str(df[key].iloc[i, j]) table.alignment = WD_TABLE_ALIGNMENT.CENTER paratotalpay = tpl.add_paragraph('Total Pay: CA$' + '{}'.format(df[key].iloc[-1, -1])) paratotalpay.alignment = WD_ALIGN_PARAGRAPH.RIGHT tpl.render(context) tpl.save( '/Users/xintongli/PycharmProjects/Project/Automatic Invoice/Dataset/Invoice/' + '{}'.format(key) + '_invoice.docx')
def write_to_word(data_id): newFileName = datetime.now().strftime("%Y-%m-%d_%H:%M:%S") + '.docx' fileName = wordName() filePath = os.path.join(path, fileName) # 定义当前时间 codes = wordList(data_id) doc = DocxTemplate(filePath) i = 1 for key, val in codes.items(): doc.add_paragraph(str(i) + '.' + key) doc.add_paragraph('') create_table(doc, val) doc.add_paragraph('') i += 1 doc.add_paragraph(''' (以下无正文) 甲方: 乙方: 法定代表人:(签字) 法定代表人:(签字) 委托代理人: 委托代理人: 开户银行; 开户银行: 银行账号: 银行账号: 签订日期: 签订日期: ''') newFilePath = PATH + '/static/files/%s' % newFileName doc.save(newFilePath) File.objects.get_or_create(name=newFileName, path=newFilePath, file_type="word文件")
'grade': list_info[0], 'studentid': list_info[1], 'name': list_info[2], 'sex': list_info[3], 'cc': list_info[4], 'xy': list_info[5], 'major': list_info[6], } document = DocxTemplate('./assets/demo.docx') document.render(data) document.save('./assets/test.docx') document = Document('./assets/test.docx') p = document.add_paragraph() table = document.tables[0] list_b = [ 14, # 0 14, # 1 0, 2, 4, 6, 8, # GPA 0, 8, 14, 0, 8, 14, # 4体测 0, 8, 0, 8, 14, # 6 四级 0, 8, 0, 8, # 8专业其他 0, # 9科技活动 0, 14, # 10学籍
def wazuh(): client = request.form['client'] sujet = request.form['sujet'] type = request.form['type'] serv = request.form['serv'] numero = request.form['numero'] img = request.form['description'] description = request.form['description'] recommandation = request.form['recommandation'] requete_wazuh = """INSERT INTO wazuh(type,numero,sujet,date,client,description,recommandation) VALUES(%s, %s, %s, %s, %s, %s)""" recordTuple = (type, numero, sujet, date, client, description, recommandation) myCursor.execute(requete_wazuh, recordTuple) mydb.commit() doc = DocxTemplate("ATB_Template.docx") context = {'Keystone': "World company"} doc.render(context) parag = doc.add_paragraph() titre1 = parag.add_run("\t \t \t \tIncident ref: ") font = titre1.font font.name = 'Calibri (Body)' font.size = Pt(16) titre2 = parag.add_run(type + "-" + date + "-" + numero + "\n") font = titre2.font font.name = 'Calibri (Body)' font.size = Pt(16) font.bold = True if (serv == "Elévé"): font.color.rgb = RGBColor(255, 0, 0) elif (serv == "Moyenne"): font.color.rgb = RGBColor(255, 128, 0) else: font.color.rgb = RGBColor(0, 153, 0) parag.add_run("\n") titre3 = parag.add_run("Sujet: " + sujet + "\n") if " " in sujet: sujet = sujet.replace(" ", "_") font = titre3.font font.name = 'Calibri (Body)' font.size = Pt(14) font.bold = True font.color.rgb = RGBColor(255, 255, 255) if (serv == "Elévé"): font.highlight_color = WD_COLOR_INDEX.RED elif (serv == "Moyenne"): font.highlight_color = WD_COLOR_INDEX.YELLOW else: font.highlight_color = WD_COLOR_INDEX.GREEN titre4 = parag.add_run("Réference: ") font = titre4.font font.name = 'Calibri (Body)' font.size = Pt(14) font.bold = True titre5 = parag.add_run(type + "-" + date + "-" + numero + "\n") font = titre5.font font.name = 'Calibri (Body)' font.size = Pt(16) font.bold = True if (serv == "Elévé"): font.color.rgb = RGBColor(255, 0, 0) elif (serv == "Moyenne"): font.color.rgb = RGBColor(255, 128, 0) else: font.color.rgb = RGBColor(0, 153, 0) titre6 = parag.add_run("Sévirité: ") font = titre6.font font.name = 'Calibri (Body)' font.size = Pt(14) font.bold = True titre7 = parag.add_run(serv + "\n") font = titre7.font font.name = 'Calibri (Body)' font.size = Pt(14) font.bold = True if (serv == "Elévé"): font.color.rgb = RGBColor(255, 0, 0) elif (serv == "Moyenne"): font.color.rgb = RGBColor(255, 128, 0) else: font.color.rgb = RGBColor(0, 153, 0) titre8 = parag.add_run("Description:\n") font = titre8.font font.name = 'Calibri (Body)' font.size = Pt(14) font.bold = True titre9 = parag.add_run(description + "\n") font = titre9.font font.name = 'Calibri (Body)' font.size = Pt(12) titre11 = parag.add_run("Source :\n") font = titre11.font font.name = 'Calibri (Body)' font.size = Pt(14) font.bold = True titre12 = parag.add_run("Wazuh \n") font = titre12.font font.name = 'Calibri (Body)' font.size = Pt(12) titre13 = parag.add_run("Recommandation :\n") font = titre13.font font.name = 'Calibri (Body)' font.size = Pt(14) font.bold = True titre14 = parag.add_run(recommandation) font = titre14.font font.name = 'Calibri (Body)' font.size = Pt(12) doc.save(client + "-" + type + "-" + date + "-" + "0" + numero + "_" + sujet + ".docx") os.system("start " + client + "-" + type + "-" + date + "-" + "0" + numero + "_" + sujet + ".docx") return render_template('/wazuh.html')
def getFootballFormatted(string_of_week_url_espn): abbr_to_num = { name: num for num, name in enumerate(calendar.month_abbr) if num } url = string_of_week_url_espn response = requests.get(url) soup = BeautifulSoup(response.content, 'lxml') #print(soup.prettify()) games = [] # a list to store games table = soup.find('div', attrs={'id': 'sched-container'}) dates = table.findAll('h2', attrs={'class': 'table-caption'}) daygamesdiv = table.findAll('div', attrs={'class': 'responsive-table-wrap'}) #if new: document = Document() instead #with lines (may need adjusting) document = DocxTemplate("line_template.docx") #for new doc #document = Document() #font = document.styles['Normal'].font #10 font, Verdana, BOLD, dark blue #document.font.name = 'Verdana' #document.font.bold = True #document.add_heading('Weekly Football Schedule', 0) text = '' daycount = 0 gamecount = 1 for daygames in daygamesdiv: formatted_date_text = '' m = re.match("(\w+),\s(\w+)\s(\d+)", dates[daycount].text) m.group(1) m.group(2) m.group(3) monthNumber = str(abbr_to_num[m.group(2)[:3]]) formatted_date_text += monthNumber + '-' + m.group(3) + ' ' + m.group( 1)[:3] daycount += 1 datetext = document.add_paragraph() datetext.paragraph_format.space_after = Pt(0) datetext_run = datetext.add_run(formatted_date_text.upper()) datetext_run.font.color.rgb = RGBColor(0x0, 0x0, 0x0) datetext_run.font.size = Pt(8) datetext_run.left_margin = Inches(.2) datetext_run.font.name = 'Verdana' datetext_run.bold = True text = '' for game in daygames.findAll('a', attrs={'class': 'team-name'}): text += game.span.text + '\n' if (gamecount % 2) == 0: text += '\n' #paragraph_format.space_after = Pt(0) gamecount += 1 text = text[:-2] paragraph = document.add_paragraph() paragraph_run = paragraph.add_run(text.upper()) paragraph_run.font.color.rgb = RGBColor(0x17, 0x24, 0x92) paragraph_run.font.size = Pt(10) paragraph_run.left_margin = Inches(.2) paragraph_run.font.name = 'Verdana' paragraph_run.bold = True paragraph.paragraph_format.space_before = Pt(0) document.save('weeklyFootball.docx') os.system('open weeklyFootball.docx')
} doc.render(context) doc.save("generated_temp.docx") # 源文件 test.docx doc = Document("generated_temp.docx") #doc = Document("牛逼哥+PXFC211507SC.docx") #styles = doc.styles # #for style in styles: # print(style.name) p1 = doc.add_paragraph('') r1 = p1.add_run('YYY的主要特点:') for i in arr1: #增加无序列表 paragraph = doc.add_paragraph(i) paragraph_format = paragraph.paragraph_format #paragraph_format.left_indent = Inches(0.291) doc.add_paragraph('') p2 = doc.add_paragraph('') r2 = p2.add_run('YYY的典型应用:')
} doc.render(context) doc.save("generated_temp.docx") # 源文件 test.docx doc = Document("generated_temp.docx") #doc = Document("刘阳+PXFC211507SC.docx") #styles = doc.styles # #for style in styles: # print(style.name) p1 = doc.add_paragraph('') r1 = p1.add_run(pick['型号'] + '的主要特点:') if pick['特性1'] != '': paragraph = doc.add_paragraph(pick['特性1']) paragraph_format = paragraph.paragraph_format if pick['特性2'] != '': paragraph = doc.add_paragraph(pick['特性2']) paragraph_format = paragraph.paragraph_format doc.add_paragraph('') p2 = doc.add_paragraph('') r2 = p2.add_run(pick['型号'] + '的典型应用:') application = pick['应用'] application = application.replace('?', '')
class MainWindow(QtGui.QDialog, Ui_MainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) self.errorPopup = MyPopup() # ---------------------------------------------------# # Local Variables # ---------------------------------------------------# # Create instance of Document.docx file self.filePath = "" self.userName = "" self.dateNow = datetime.datetime.now().date().strftime("%m-%d-%Y") self.projectName = "" self.document = DocxTemplate(cwd + "/default.docx") self.tableRowCount = 0 # ---------------------------------------------------# # file name Variables -- add to list if additional # files are parsed in future # ---------------------------------------------------# self.fsum = "" self.fsum_erc = "" self.fcls = "" self.flog = "" self.fascii = "" self.fpictures = [] # ---------------------------------------------------# # User Interface Property changes # ---------------------------------------------------# self.date.setText("Date: " + self.dateNow) # ---------------------------------------------------# # Call appropriate function on user actions # ---------------------------------------------------# self.okButton.clicked.connect(self.systemHandler) self.toolButton.clicked.connect(self.openExplorer) self.cancelButton.clicked.connect(self.closeApplication) # ----------------------------------------------------------------------------# # # Function Name: closeApplication() # Description: Called whenever cancel button is clicked by user. The # application will close # Last Edited: 11/05/2016 # Last Edited By: Jonathan Wesner # Last Changes Made: ... # # ----------------------------------------------------------------------------# def closeApplication(self): sys.exit(app.exec_()) def openExplorer(self): fileDirectory = QtGui.QFileDialog.getExistingDirectory( self, "Select Directory") self.fileInput.setText(fileDirectory) def systemHandler(self): # ------------------------------------------------------------------------# # Handle file path error checking # ------------------------------------------------------------------------# self.filePath = str(self.fileInput.text()) # Check that file path is valid if not os.path.exists(os.path.dirname(self.filePath)): self.displayError("File path provided not found.") return # ------------------------------------------------------------------------# # Handle user Name and Project Name and check that user has not left # blank. # ------------------------------------------------------------------------# self.userName = str(self.userNameEdit.text()) self.projectName = str(self.projectNameEdit.text()) if (self.userName is "") or (self.projectName is ""): self.displayError( "Please fill all fields including User Name and Project Name.") return # ------------------------------------------------------------------------# # Set title information and styling of Word Document here # ------------------------------------------------------------------------# style = self.document.styles['Normal'] font = style.font font.name = 'Calibri' font.size = Pt(10) self.printToDocument( 'Project Name: ' + self.projectName + '\n' + 'Tape-out Date: ' + str(self.dateNow) + '\n' + 'Preparer: ' + self.userName + '\n\n', True) # ------------------------------------------------------------------------# # Add Title Table # table.cell(Row,Column) --- reference # ------------------------------------------------------------------------# self.tableRowCount = 0 self.table = self.document.add_table(rows=0, cols=4) self.table.style = 'Light Shading' self.fillTable('File name', 'Description', 'File size (bytes)', 'Date/Time') # parse files and fill table self.getFileNames() self.document.add_page_break() # ------------------------------------------------------------------------# # Error check all files are present before continuing # ------------------------------------------------------------------------# if self.fsum == "": self.displayError( "No .sum file exists. Please include file in folder before continuing." ) return if self.fsum_erc == "": self.displayError( "No .sum_erc file exists. Please include file in folder before continuing." ) return if self.fcls == "": self.displayError( "No .rep.cls file exists. Please include file in folder before continuing." ) return if self.fascii == "": self.displayError( "No .drc_errors.ascii file exists. Please include file in folder before continuing." ) return if self.flog == "": self.displayError( "No .sum_erc file exists. Please include file in folder before continuing." ) return # ------------------------------------------------------------------------# # Order of Looking for files -- add to list as needed # 1) .sum file # 2) .ascii file (used to output errors of .sum file) # 3) .cls file # 4) .sum_erc # 5) .log # 6) .png or jpg (add pictures last) # ------------------------------------------------------------------------# collectErrors = "" # first argument of searchSumFile() takes in file name, second argument # allows for the collection of the summary section of the file self.printToDocument('DRC:', True) # Order File look up #1 collectErrors = self.searchSumFile(self.fsum, False) # Order File look up #2 self.printToDocument("DRC Errors:", True) self.sumFileErrors(collectErrors, self.fascii) # Order File look up #3 self.printToDocument("LVS:", True) self.searchClsFile(self.fcls) # Order File look up #4 collectErrors = "" self.printToDocument("ERC:", True) collectErrors = self.searchSumFile(self.fsum_erc, True) # Order File look up #5 self.printToDocument("ERC Errors:", True) self.sumErcFileErrors(collectErrors, self.flog) # Add pictures here...order file look up #6 self.printToDocument("Images:", True) if self.fpictures is not None: for img in self.fpictures: self.document.add_picture(img, width=Inches(3), height=Inches(3)) # Save document self.document.save(self.filePath + '/summary.docx') # Message to user that file is done self.displayError( "File is Complete! File saved in folder where other files were specified.", "ATTENTION!") self.fileInput.setText("") self.userNameEdit.setText("") self.projectNameEdit.setText("") # ----------------------------------------------------------------------------# # # Function Name: getFileNames() # Description: This function takes care of grabing the file names needed to be # opened. It uses the filePath variable to look for the files. # Current files being read in are in this order... # 1) .sum file # 2) .ascii file (used to output errors of .sum file) # 3) .cls file # 4) .sum_erc file # 5) .log file # 6) .png or jpg(add pictures last) # Last Edited: 11/05/2016 # Last Edited By: Jonathan Wesner # Last Changes Made: ... # # ----------------------------------------------------------------------------# def getFileNames(self): files = os.walk(self.filePath, topdown=False) for fileName in os.listdir(self.filePath): # --------------------------------------------------------------------# # get all files in folder and print out info to a table # --------------------------------------------------------------------# f = os.path.join(self.filePath, fileName) fileStats = os.stat(f) fileSize = fileStats.st_size dateLastModified = fileStats.st_mtime timeFormatted = datetime.datetime.fromtimestamp( int(dateLastModified)).strftime('%Y-%m-%d %H:%M:%S') self.fillTable(fileName, "", fileSize, timeFormatted) # --------------------------------------------------------------------# # check what type fileName is and fill the variables # --------------------------------------------------------------------# if fileName.endswith(".sum_erc"): self.fsum_erc = os.path.join(self.filePath, fileName) elif fileName.endswith(".sum"): self.fsum = os.path.join(self.filePath, fileName) elif fileName.endswith(".log"): if fileName.endswith(".streamout"): return self.flog = os.path.join(self.filePath, fileName) elif fileName.endswith(".rep.cls"): self.fcls = os.path.join(self.filePath, fileName) elif fileName.endswith(".drc_errors.ascii"): self.fascii = os.path.join(self.filePath, fileName) else: if fileName.endswith(".png") or fileName.endswith(".jpg"): self.fpictures.append(os.path.join(self.filePath, fileName)) # ----------------------------------------------------------------------------# # # Function Name: fillTable() # Description: This function takes in four data strings from each file # that will be parsed and fills a table with the individual # attributes of each file... # Last Edited: 10/29/2016 # Last Edited By: Jonathan Wesner # Last Changes Made: ... # # ----------------------------------------------------------------------------# def fillTable(self, fileName, fileDescription, fileSize, fileDateTime): # Add Row self.table.add_row() # Define each column of the table before setting the values fName = self.table.cell(self.tableRowCount, 0) fDescription = self.table.cell(self.tableRowCount, 1) fSize = self.table.cell(self.tableRowCount, 2) fDateTime = self.table.cell(self.tableRowCount, 3) # fill each cell from passed in strings fName.text = fileName fDescription.text = fileDescription fSize.text = str(fileSize) fDateTime.text = fileDateTime # Add to tableRowCount self.tableRowCount = self.tableRowCount + 1 # ----------------------------------------------------------------------------# # # Function Name: printToDocument() # Description: This function handles creating a new paragraph to the document. # It takes in a string and will pass that string to the document. # Last Edited: 10/27/2016 # Last Edited By: Jonathan Wesner # Last Changes Made: ... # # ----------------------------------------------------------------------------# def printToDocument(self, string, isBold=False): output = self.document.add_paragraph() output.add_run(string).bold = isBold # ----------------------------------------------------------------------------# # # Function Name: searchSumFile() # Description: This function handles searching the .sum file. It parses # through the header of the file, and finds any errors under the # RULECHECK section of the file. These errors are collected and # passed to the sumFileErrors() function, which outputs the # details of the errors from the drc_errors.ascii file. # Last Edited: 10/27/2016 # Last Edited By: Jonathan Wesner # Last Changes Made: ... # # ----------------------------------------------------------------------------# def searchSumFile(self, fileToSearch, getSummary): sumFileHeader = "" sumFileSummary = "" sumHeaderDone = False summarySection = False sumCollectErrors = "" headerCount = 0 # ------------------------------------------------------------------------# # Open .sum file and parse through to grab header/summary, and any errors # ------------------------------------------------------------------------# sumFile = open(fileToSearch, 'r') for line in sumFile: if (('------' in line) or ('******' in line)) and (sumHeaderDone is False): headerCount = headerCount + 1 if headerCount > 1: sumHeaderDone = True sumFileHeader = sumFileHeader + line # Check for header finish if sumHeaderDone is False: sumFileHeader = sumFileHeader + line # Check for errors in file if sumHeaderDone: if ("RULECHECK " in line) and ("Total Result 0 ( 0)" not in line): sumCollectErrors = sumCollectErrors + " " + re.search( 'RULECHECK (.+?) ....', line).group(1) + " " # Parse through summary of file if getSummary: if "--- SUMMARY" in line: summarySection = True if summarySection: sumFileSummary = sumFileSummary + line # print header to document self.printToDocument(sumFileHeader) # print summary to header if needed if getSummary: self.printToDocument(sumFileSummary) # Close file sumFile.close() return sumCollectErrors # ----------------------------------------------------------------------------# # # Function Name: sumFileErrors() # Description: This function is called by searchSumFile() and outputs # details about the particular errors found in the # searchSumFile(). # Last Edited: 10/27/2016 # Last Edited By: Jonathan Wesner # Last Changes Made: ... # # ----------------------------------------------------------------------------# def sumFileErrors(self, errorsToSearch, errorFileToSearch): checkStatus = False sumErrors = "" errorFile = open(errorFileToSearch, 'r') for line in errorFile: # remove '\n' at end of line stripLine = line.rstrip() result = re.search(stripLine, errorsToSearch) if checkStatus is True: sumErrors = sumErrors + line if error in stripLine: sumErrors = sumErrors + "\n" checkStatus = False if result is not None: checkStatus = True error = stripLine sumErrors = sumErrors + line self.printToDocument(sumErrors) errorFile.close() # ----------------------------------------------------------------------------# # # Function Name: sumFileErrors() # Description: This function is called by searchSumFile() and outputs # details about the particular errors found in the # .sum_erc file # Last Edited: 10/29/2016 # Last Edited By: Jonathan Wesner # Last Changes Made: ... # # ----------------------------------------------------------------------------# def sumErcFileErrors(self, errorsToSearch, errorFileToSearch): sumErrors = "" errorFile = open(errorFileToSearch, 'r') errorFound = False errorsToSearch = re.findall('ERC(.+?) ', errorsToSearch) for line in errorFile: # remove '\n' at end of line if errorFound: sumErrors = sumErrors + line if "}" in line: errorFound = False else: for error in errorsToSearch: if (('RULE ERC' + error + " {") in line): sumErrors = sumErrors + line errorFound = True break self.printToDocument(sumErrors) errorFile.close() # ----------------------------------------------------------------------------# # # Function Name: searchClsFile() # Description: This function is searches for and prints out the header # in the .cls file. # Last Edited: 10/27/2016 # Last Edited By: Jonathan Wesner # Last Changes Made: ... # # ----------------------------------------------------------------------------# def searchClsFile(self, fileToSearch): clsHeaderDone = False clsFileHeader = "" headerCount = 0 clsFile = open(fileToSearch, 'r') for line in clsFile: if ('###########' in line) and (clsHeaderDone == False): headerCount = headerCount + 1 if headerCount > 1: clsHeaderDone = True clsFileHeader = clsFileHeader + line if clsHeaderDone == False: clsFileHeader = clsFileHeader + line self.printToDocument(clsFileHeader) clsFile.close() # ############################################################################# # # Function Description: This function is called whenever an error message # needs to be displayed to the screen. # Last Edited: 11/12/2016 # Last Edited By: Jonathan Wesner # Last Changes Made: ... # # ############################################################################# def displayError(self, errorText, title="ERROR!"): self.errorPopup.errorMessage.setText(errorText) self.errorPopup.title.setText(title) # Freezes the Main Window till a response is made by the user for MyPopup() self.errorPopup.setWindowModality(QtCore.Qt.ApplicationModal) self.errorPopup.show()