python讀寫word文檔有現成的庫可以處理,在這里采用了 python-docx。
首先先安裝
pip install python-docx
#!/usr/bin/env python # -*- coding:utf-8 -*- import sys, os import django sys.path.append('../') os.environ['DJANGO_SETTINGS_MODULE'] = 'web.settings' #setting的目錄 django.setup() from django.apps import apps as django_apps from utils.papergen.report.device_constructor import DeviceConstructor type = sys.getfilesystemencoding() # 設置默認編碼 type = sys.getfilesystemencoding() def main(): wd = DeviceConstructor.construct("docx") wd.add_title({"data": u"人物檔案", "level": 1}) #創建一級標題 all_apps = django_apps.get_models() for app in all_apps: wd.add_title({"data": [u"人員基本信息:%s 數據庫表名稱:%s" % (app._meta.label, app._meta.db_table)], "level": 1}) #創建標題 temp_list = [[u"字段名稱", u"中文字段名稱", u"字段類型"],] for field in app._meta.fields: # text = u"%s,%s,%s" % (unicode(field.verbose_name), field.name, field.get_internal_type()) # wd.add_text(text) temp_list.append([unicode(field.verbose_name), field.name, field.get_internal_type()]) wd.add_table({'rows': len(temp_list), 'cols': 3, "data": temp_list}) # 創建表格
wd.save("person.docx") #保存
想要下載下來的話:
response = HttpResponse(content_type='text/docx') response['Content-Disposition'] = 'attachment; filename=%s.docx' % pk wd.save(response) return response
參考:http://python-docx.readthedocs.io/en/latest/