1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
| from docx import Document from docx.oxml.ns import qn from docx.shared import Pt,Cm,RGBColor from docx.enum.text import WD_ALIGN_PARAGRAPH,WD_PARAGRAPH_ALIGNMENT from docx.enum.table import WD_ALIGN_VERTICAL from docx.enum.text import WD_UNDERLINE from docx import shared from docx.enum.section import WD_ORIENT from docx.enum.text import WD_TAB_ALIGNMENT from add_float_picture import add_float_picture from extract_content_from_docx import extract_content_from_docx from docx.enum.style import WD_STYLE_TYPE from docx.oxml import OxmlElement from docx.oxml import parse_xml from docx.oxml.ns import nsdecls import datetime import os from mssql import closeConn, connectMSsql, executeSQL from loguru import logger import re
FileLog = 'log{}.log'.format(datetime.date.today()) logger.add(FileLog,rotation="500MB", encoding="utf-8", enqueue=True)
def P0Content(num,date): content1 = document.add_paragraph('\n\n\n\n\n\n\n\n\n\n\n') content1Run = content1.add_run('公 司 经 营 情 况 周 报\n') content1Run.font.name = '彩虹小标宋' content1Run._element.rPr.rFonts.set(qn('w:eastAsia'),'彩虹小标宋') content1Run.font.size = Pt(22) content1Run.bold = True content1.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER add_float_picture(content1,'D:/workspace/weeklyNewspaper/img/P1_logo.png',height=shared.Cm(2.3),pos_x=shared.Cm(3.17),pos_y=shared.Cm(4.5)) add_float_picture(content1,'D:/workspace/weeklyNewspaper/img/P1_banner1.png',height=shared.Cm(6.11),pos_x=shared.Cm(-3.23),pos_y=shared.Cm(8)) numPara = document.add_paragraph('第{}期({})'.format(num,date)) numPara.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
def L1(content): head1 = document.add_heading('', level = 1) head1.add_run(content)
def L2(content): head2 =document.add_heading('',level = 2) head2.add_run(content)
def L0(content): lines = content.split('\n') new_lines = [line for line in lines if line.strip()!=''] for i in new_lines: par = document.add_paragraph(i) par.paragraph_format.first_line_indent = Pt(28)
def set_table_boarder(table,**kwargs): borders = OxmlElement('w:tblBorders') for tag in ('bottom','top','left','right','insideV','insideH'): edge_data = kwargs.get(tag) if edge_data: any_border = OxmlElement(f'w:{tag}') for key in ['sz','val','color','space','shadow']: if key in edge_data: any_border.set(qn(f'w:{key}'),str(edge_data[key])) borders.append(any_border) table._tbl.tblPr.append(borders)
def insertTable(row,col): table = document.add_table(row,col) set_table_boarder(table, top = {'sz':4,'val':'single','color':'#000000'}, bottom = {'sz':4,'val':'single','color':'#000000'}, left = {'sz':4,'val':'single','color':'#000000'}, right = {'sz':4,'val':'single','color':'#000000'}, insideV = {'sz':4,'val':'single','color':'#000000'}, insideH = {'sz':4,'val':'single','color':'#000000'}) return table
def AddFooterNumber(run): fldChar1 = OxmlElement('w:fldChar') fldChar1.set(qn('w:fldCharType'), 'begin') instrText = OxmlElement('w:instrText') instrText.set(qn('xml:space'), 'preserve') instrText.text = 'Page' fldChar2 = OxmlElement('w:fldChar') fldChar2.set(qn('w:fldCharType'), 'separate') t = OxmlElement('w:t') t.text = "Seq" fldChar2.append(t) fldChar4 = OxmlElement('w:fldChar') fldChar4.set(qn('w:fldCharType'), 'end') r_element = run._r r_element.append(fldChar1) r_element.append(instrText) r_element.append(fldChar2) r_element.append(fldChar4)
def InsertPageNumber(footer):
footer.is_linked_to_previous = True paragraph = footer.paragraphs[0] paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER run_footer=paragraph.add_run() AddFooterNumber(run_footer) font = run_footer.font font.name = 'Times New Roman' font.size = Pt(10) font.bold = True
def headerParagraphs0(hNum,hDate): document.sections[0].top_margin = Cm(2.54) document.sections[0].bottom_margin = Cm(2.54) document.sections[0].left_margin = Cm(3.17) document.sections[0].rigth_margin = Cm(3) run0 = document.sections[0].footer.paragraphs[0] run0Style = run0.add_run('注:资产处置总部的周报相关内容由资产处置总部另行每周报送。') run0Style.font.name = '彩虹粗仿宋' run0Style._element.rPr.rFonts.set(qn('w:eastAsia'),'彩虹粗仿宋') run0Style.font.size = Pt(10.5)
def headerParagraphs1(hNum,hDate): document.add_section() document.sections[1].top_margin = Cm(2.54) document.sections[1].bottom_margin = Cm(2.54) document.sections[1].left_margin = Cm(3.17) document.sections[1].right_margin = Cm(3) document.sections[1].header.is_linked_to_previous = False run1 = document.sections[1].header.paragraphs[0] run1Style = run1.add_run('公司经营情况周报[第{}期({})]'.format(hNum,hDate)) run1Style.font.name = '彩虹粗仿宋' run1Style._element.rPr.rFonts.set(qn('w:eastAsia'),'彩虹粗仿宋') run1Style.font.size = Pt(10.5) add_float_picture(run1,'D:/workspace/weeklyNewspaper/img/yemei_logo.png',height=shared.Cm(0.8),pos_x=shared.Cm(15.19),pos_y=shared.Cm(0.95)) run1.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER document.sections[1].footer.is_linked_to_previous = False
def headerParagraphs2(hNum,hDate): document.add_section() document.sections[2].top_margin = Cm(3.17) document.sections[2].bottom_margin = Cm(3) document.sections[2].left_margin = Cm(2.54) document.sections[2].right_margin = Cm(2.54) document.sections[2].header.is_linked_to_previous = False run2 = document.sections[2].header.paragraphs[0] run2Style = run2.add_run('\t公司经营情况周报[第{}期({})]\t'.format(hNum,hDate)) run2Style.font.name = '彩虹粗仿宋' run2Style._element.rPr.rFonts.set(qn('w:eastAsia'),'彩虹粗仿宋') run2Style.font.size = Pt(10.5) add_float_picture(run2,'D:/workspace/weeklyNewspaper/img/yemei_logo.png',height=shared.Cm(0.8),pos_x=shared.Cm(20),pos_y=shared.Cm(0.95)) run2.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER document.sections[2].footer.is_linked_to_previous = False
def PaperOrientation(num): section = document.sections[num-1] new_width,new_height = section.page_height,section.page_width section.orientation = WD_ORIENT.LANDSCAPE section.page_width = new_width section.page_height = new_height
def Table_Line_Repeat(doc,firstcell): for table in doc.tables: if table.cell(0,0).text.strip() == firstcell: row = table.rows[0] tr = row._element trPr = tr.get_or_add_trPr() tblHeader = OxmlElement('w:tblHeader') tblHeader.set(qn('w:val'), "true") trPr.append(tblHeader) return doc
if __name__ == '__main__': logger.info('***开始处理word文档***') sqlConnectParams = {"database_name": "****", "username": "****", "password": "****", "host": "****", "port": "****", "encoding": "cp936"} deptSqlQuery = "select (case when c.xsmc is null then d.departmentmark else c.xsmc end) ,e.gzsxmc,e.bzjzqk,e.xzgzap from formtable_main_246 a left join workflow_requestbase b on a.requestid=b.requestid left join uf_comweeklyorder c on c.bm=a.ngbm left join HrmDepartment d on d.id=a.ngbm left join formtable_main_246_dt1 e on e.mainid=a.id where b.currentnodetype=3 and c.bm is not null and b.createdate>=CONVERT ( CHAR ( 10 ), getdate()-5, 120 ) order by c.scsx,e.id" numSqlQuery = "select top 1 num,replace(createdate,'-','') from uf_comweeklyset where isnull(flag,1)!=0 order by num " conn = connectMSsql(sqlConnectParams) logger.info('***已连接数据库***') lista = executeSQL(conn,deptSqlQuery) numdetail =executeSQL(conn,numSqlQuery) logger.info('***已获取职能部门周报清单***') num = numdetail[0][0] date = numdetail[0][1] logger.info('***已获取此次周报期号及生成日期***') path = 'D:/aidownload/gongsizhoubao/{}'.format(datetime.datetime.today().date()) document = Document('D:/workspace/weeklyNewspaper/module.docx') logger.info('***word模板调用完成***') headerParagraphs0(num,date) P0Content(num,date) logger.info('***第一节处理完成***') headerParagraphs1(num,date) for i in os.listdir(path): logger.info('***开始处理:{}***'.format(i)) document_content = extract_content_from_docx(path+'/'+i) for category,level, data in document_content: if category == 'paragraph': if level == 'L0': L0(data) elif level == 'L1': L1(data) elif level == 'L2': L2(data) elif category == 'table': L0('【插入表格】')
logger.info('***第二节处理完成***') headerParagraphs2(num,date) PaperOrientation(3) L1('职能部门') table = insertTable(len(lista)+1,4) listb = [['填报部门','工作事项名称','本周进展情况','下周工作安排']] for i in lista: listc = [] for j in i : b = j.replace('<br>','\n') listc.append(b) listb.append(listc) for i in range(0,len(listb)-1): for j in range(i+1,len(listb)): if listb[i][0] == listb[j][0]: listb[j][0] = '' table.cell(i,0).merge(table.cell(j,0)) for rowa in table.rows: rowa.cells[0].width = Cm(2.55) rowa.cells[1].width = Cm(3) rowa.cells[2].width = Cm(9.94) rowa.cells[3].width = Cm(9.71) for i,row in enumerate(table.rows): for j,cell in enumerate(row.cells): if listb[i][j] != '': if i!=0 and j>1 and listb[i][j][-1] not in [';','。',':']: listb[i][j] = listb[i][j]+'。' listb[i][j] = re.sub(r'(?<![;。:])\n','。\n',listb[i][j]) listb[i][j] = re.sub(r'\n(\d)(?!\d)',r'\n\1.',listb[i][j]) listb[i][j] = re.sub(r'(?<=\n(\d\.))[ ,。、.]','',listb[i][j]) table.cell(i,j).text = listb[i][j] try : cell.paragraphs[0].runs[0].font.size = Pt(11) except IndexError as e: pass if i == 0: cell.paragraphs[0].runs[0].bold = True cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER else : cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.LEFT cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER InsertPageNumber(document.sections[2].footer) Table_Line_Repeat(document,"填报部门") document.save('{}/公司周报{}.docx'.format(path,datetime.datetime.today().date())) logger.info('***第三节处理完成***') numSqlUpdate = "update uf_comweeklyset set flag=0,ts={} where num={}".format(date,num) executeSQL(conn,numSqlUpdate) closeConn(conn) logger.info('***处理结束,更新处理状态***')
|