[{"data":1,"prerenderedAt":259},["ShallowReactive",2],{"content-query-hrlgL3KBuR":3},{"_path":4,"_dir":5,"_draft":6,"_partial":6,"_locale":7,"title":8,"description":9,"date":10,"cover":11,"type":12,"category":13,"body":14,"_type":253,"_id":254,"_source":255,"_file":256,"_stem":257,"_extension":258},"/technology-blogs/zh/784","zh",false,"","python在手，word不愁","python办公系列来咯","2021-11-12","https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2021/11/12/b8d8ff27b16a45b4ae93be7b0db6677e.png","technology-blogs","基础知识",{"type":15,"children":16,"toc":243},"root",[17,25,31,44,49,59,67,72,83,88,93,101,106,113,122,127,132,137,142,149,154,162,167,174,179,188,193,198,206,211,219,224,229],{"type":18,"tag":19,"props":20,"children":22},"element","h1",{"id":21},"python在手word不愁",[23],{"type":24,"value":8},"text",{"type":18,"tag":26,"props":27,"children":28},"p",{},[29],{"type":24,"value":30},"时隔好久，这不小Mi的python办公系列又更新啦！这次我们学习如何用python处理word文件！",{"type":18,"tag":32,"props":33,"children":35},"h2",{"id":34},"_1-安装库",[36,38],{"type":24,"value":37},"1. ",{"type":18,"tag":39,"props":40,"children":41},"strong",{},[42],{"type":24,"value":43},"安装库",{"type":18,"tag":26,"props":45,"children":46},{},[47],{"type":24,"value":48},"说实话，库的安装其实相比excel来说真的就再简单不过啦，这次小Mi全程就只更新安装了一个库，代码如下：",{"type":18,"tag":50,"props":51,"children":53},"pre",{"code":52},"pip install python-docx\n",[54],{"type":18,"tag":55,"props":56,"children":57},"code",{"__ignoreMap":7},[58],{"type":24,"value":52},{"type":18,"tag":26,"props":60,"children":61},{},[62],{"type":18,"tag":63,"props":64,"children":66},"img",{"alt":7,"src":65},"https://bbs-img.huaweicloud.com/data/forums/attachment/forum/202111/12/160301sldobclc2px830we.png",[],{"type":18,"tag":26,"props":68,"children":69},{},[70],{"type":24,"value":71},"欧凯，那么这部分就已经完成啦！（是不是超简单）",{"type":18,"tag":32,"props":73,"children":75},{"id":74},"_2-简单炫技",[76,78],{"type":24,"value":77},"2. ",{"type":18,"tag":39,"props":79,"children":80},{},[81],{"type":24,"value":82},"简单炫技",{"type":18,"tag":26,"props":84,"children":85},{},[86],{"type":24,"value":87},"这个时候小Mi很执拗，并不想走寻常路，只想用python编写一个word文件怎么办！小Mi告诉你，依旧很简单！",{"type":18,"tag":26,"props":89,"children":90},{},[91],{"type":24,"value":92},"代码参考如下：",{"type":18,"tag":50,"props":94,"children":96},{"code":95},"from docx import Document   # 导入相关库\n\nfrom docx.shared import Inches,Cm,Pt\n\nfrom docx.document import Document as Doc  \n\ndocument = Document()  # type: Doc\n\n# 添加大标题（上面一行的注释也非常重要，否则无法获得提示）\n\ndocument.add_heading('快来MindSpore昇思论坛~', 0)\n\n# 添加段落\n\np = document.add_paragraph('MindSpore是由华为于2019年8月推出的新一代全场景AI计算框架,它')\n\nrun = p.add_run('开发友好、运行高效、部署灵活！')\n\nrun.bold = True  # 对run函数的内容进行加粗\n\nrun.font.size = Pt(26)  # 设置字体的大小\n\n# 添加图片\n\ndocument.add_picture('banner.png', width=Cm(10.4))\n\n# 添加分页符\n\ndocument.add_page_break()\n\n# 保存文档\n",[97],{"type":18,"tag":55,"props":98,"children":99},{"__ignoreMap":7},[100],{"type":24,"value":95},{"type":18,"tag":26,"props":102,"children":103},{},[104],{"type":24,"value":105},"运行效果：",{"type":18,"tag":26,"props":107,"children":108},{},[109],{"type":18,"tag":63,"props":110,"children":112},{"alt":7,"src":111},"https://bbs-img.huaweicloud.com/data/forums/attachment/forum/202111/12/16045384ylian25r7ybgx3.png",[],{"type":18,"tag":32,"props":114,"children":116},{"id":115},"_3高级炫技",[117],{"type":18,"tag":39,"props":118,"children":119},{},[120],{"type":24,"value":121},"3.高级炫技",{"type":18,"tag":26,"props":123,"children":124},{},[125],{"type":24,"value":126},"太简单了！真的是没有任何难度，所以这不小Mi需要给大家表演一个魔术！",{"type":18,"tag":26,"props":128,"children":129},{},[130],{"type":24,"value":131},"假设场景：",{"type":18,"tag":26,"props":133,"children":134},{},[135],{"type":24,"value":136},"我们经常是不是需要处理很多文件，这些文件是不是都很类似，那么是不是可以设计一个模板出来，在需要大量编写这些word文件的时候，几行代码轻松搞定！比如公司入职人员的信息统计。",{"type":18,"tag":26,"props":138,"children":139},{},[140],{"type":24,"value":141},"首先设定一个简单的word模板：",{"type":18,"tag":26,"props":143,"children":144},{},[145],{"type":18,"tag":63,"props":146,"children":148},{"alt":7,"src":147},"https://bbs-img.huaweicloud.com/data/forums/attachment/forum/202111/12/160557bqmn1pvnhcdejioa.png",[],{"type":18,"tag":26,"props":150,"children":151},{},[152],{"type":24,"value":153},"然后非常高傲地附上代码：",{"type":18,"tag":50,"props":155,"children":157},{"code":156},"from docx import Document\n\nfrom docx.document import Document as Doc\n\n \n\ncontracts = [\n\n    {\n\n        'company': 'A',\n\n        'number': '000451',\n\n        'start': '2020.1.6',\n\n    },\n\n    {\n\n        'company': 'B',\n\n        'number': '000452',\n\n        'start': '2021.6.4',\n\n    },\n\n    {\n\n        'company': 'C',\n\n        'number': '000453',\n\n        'start': '2021.10.9',\n\n    },\n\n]\n\n \n\nfor emp_dict in contracts:\n\n    doc = Document('信息统计.docx')  # type: Doc\n\n    for p in doc.paragraphs:\n\n        if '{' not in p.text:\n\n            continue\n\n        for run in p.runs:\n\n            if '{' not in run.text:\n\n                continue\n\n            # 将占位符换成实际内容\n\n            start, end = run.text.find('{'), run.text.find('}')\n\n            key, place_holder = run.text[start + 1:end], run.text[start:end + 1]\n\n            run.text = run.text.replace(place_holder, emp_dict[key])\n\n\n    doc.save(f'{emp_dict[\"company\"]}信息统计.docx')\n",[158],{"type":18,"tag":55,"props":159,"children":160},{"__ignoreMap":7},[161],{"type":24,"value":156},{"type":18,"tag":26,"props":163,"children":164},{},[165],{"type":24,"value":166},"那么运行之后便可以见证奇迹啦！",{"type":18,"tag":26,"props":168,"children":169},{},[170],{"type":18,"tag":63,"props":171,"children":173},{"alt":7,"src":172},"https://bbs-img.huaweicloud.com/data/forums/attachment/forum/202111/12/1607427jl4xyn3crmymnjh.png",[],{"type":18,"tag":26,"props":175,"children":176},{},[177],{"type":24,"value":178},"文件夹中多出了三个员工信息的word文件，真的是快捷而又高级！",{"type":18,"tag":32,"props":180,"children":182},{"id":181},"_4-附赠技能",[183],{"type":18,"tag":39,"props":184,"children":185},{},[186],{"type":24,"value":187},"4 附赠技能",{"type":18,"tag":26,"props":189,"children":190},{},[191],{"type":24,"value":192},"当然啦，小Mi的word都只是简单的内容而已，大家可以在这个基础上不断地提升！",{"type":18,"tag":26,"props":194,"children":195},{},[196],{"type":24,"value":197},"比如如何添加各种标题：",{"type":18,"tag":50,"props":199,"children":201},{"code":200},"Doc = Document()\n\nDoc.add_heading(\"这是一级标题\",level=1)\n\nDoc.add_heading(\"这是二级标题\",level=2)\n\nDoc.add_heading(\"这是三级标题\",level=3)\n\nDoc.add_heading(\"这是四级标题\",level=4)\n\nDoc.save(\"标题.docx\")\n",[202],{"type":18,"tag":55,"props":203,"children":204},{"__ignoreMap":7},[205],{"type":24,"value":200},{"type":18,"tag":26,"props":207,"children":208},{},[209],{"type":24,"value":210},"比如字体设置：",{"type":18,"tag":50,"props":212,"children":214},{"code":213},"#英文字体\n\nrun = doc1.add_paragraph('设置英文字体：').add_run('This Font is Times New Roman ')\n\nrun.font.name = 'Times New Roman'\n\n#中文字体\n\nrun = doc1.add_paragraph('设置中文字体：').add_run('字体为黑体')\n\nrun.font.name='黑体'\n\nr = run._element\n\nr.rPr.rFonts.set(qn('w:eastAsia'), '黑体')\n\n#设置字体颜色\n\nrun = doc1.add_paragraph('这段为红色：').add_run('这里为红色')\n\nrun.font.color.rgb = RGBColor(0xFF, 0x00, 0x00)\n",[215],{"type":18,"tag":55,"props":216,"children":217},{"__ignoreMap":7},[218],{"type":24,"value":213},{"type":18,"tag":26,"props":220,"children":221},{},[222],{"type":24,"value":223},"好啦，今天的炫技到底结束，这个系列下期给大家推出PDF相关内容！",{"type":18,"tag":26,"props":225,"children":226},{},[227],{"type":24,"value":228},"不过需要提醒大家的是，代码里面有陷阱哦，第一个找出来的兄弟姐们直接送上我们的纪念品！另外其他复现的盆友们留言抽20-30送！！！（留言形式“复现截图+邮箱+华为云ID”），参加的人越多我们抽奖的人数就越多哦，dddd（懂得都懂！）",{"type":18,"tag":26,"props":230,"children":231},{},[232,234],{"type":24,"value":233},"更多全面用法可以参考：",{"type":18,"tag":235,"props":236,"children":240},"a",{"href":237,"rel":238},"https://bbs.huaweicloud.com/forum/thread-168953-1-1.html#",[239],"nofollow",[241],{"type":24,"value":242},"https://docxtpl.readthedocs.io/en/latest/",{"title":7,"searchDepth":244,"depth":244,"links":245},4,[246,249,251,252],{"id":34,"depth":247,"text":248},2,"1. 安装库",{"id":74,"depth":247,"text":250},"2. 简单炫技",{"id":115,"depth":247,"text":121},{"id":181,"depth":247,"text":187},"markdown","content:technology-blogs:zh:784.md","content","technology-blogs/zh/784.md","technology-blogs/zh/784","md",1776506141192]