用Python将Word中的内容写入Excel
来源:互联网 发布:云计算 中国 编辑:程序博客网 时间:2024/05/20 06:05
下载Python和依赖的库
python-docx读取Word的库
官网:http://python-docx.readthedocs.io/en/latest/
读取Excel的库:xlrd
写入Excel的库:xlwt
两者的帮助库:xlutils
官网:http://www.python-excel.org/
在命令行中输入以下命令即可
pip install python-docx#安装python-docx依赖库pip install xlrd#读Excel的库pip install xlwt#写Excel的库pip install xlutils#复制Excel的库
因为LZ是以.doc格式的Word文档,需要转为docx才能被这些库打开,因此用pywin32把.doc的文件转为.docx的文件,并且把转换的相关信息写到一个Excel里面
下载和安装pywin32的参考地址如下:
http://www.2cto.com/database/201612/576890.html
如果需要直接修改一下输入和输出目录
# _*_ coding:utf-8 _*_import osimport win32comimport xlwtfrom win32com.client import Dispatchimport sysreload(sys)sys.setdefaultencoding('utf-8')#要转换的doc文件目录docDir = r'C:\Users\Administrator\Desktop\井陉矿区\井陉矿区'#转换成功的docx文件目录docxDir = r'D:\data\data10'#包含转换信息的文件,主要包括转换成功的文件,转换失败的文件msgExcel = r'D:\data\data10\转换信息表1.xls'#文件总数fileTotal = 0#转换正确的文件总数successList = []#装换错误的文件总数errorList = []#将转换信息写入到excel中def writeMsg(): excel = xlwt.Workbook(encoding='utf-8') # 这个是指定sheet页的名称 sheet1 = excel.add_sheet('统计信息') sheet2 = excel.add_sheet('详细信息') sheet1.write(0, 0, '文件总数') sheet1.write(0, 1, '录入正确') sheet1.write(0, 2, '录入错误') sheet1.write(1, 0, fileTotal) sheet1.write(1, 1, len(successList)) sheet1.write(1, 2, len(errorList)) sheet2.write(0, 0, '录入正确') sheet2.write(0, 1, '录入错误') row = 1 for x in successList: sheet2.write(row, 0, x) row += 1 row = 1 for x in errorList: sheet2.write(row, 1, x) row += 1 excel.save(msgExcel.decode('utf-8'))if __name__ == "__main__": word = win32com.client.Dispatch('word.application') word.DisplayAlerts = 0 word.visible = 0 PATH = unicode(docDir, 'utf8') for root, dirs, files in os.walk(PATH): fileTotal = len(files) for name in files: fileName = os.path.join(root, name) print fileName try: doc = word.Documents.Open(fileName) #这个是保存的目录 doc.SaveAs(docxDir + "\\" + fileName.split("\\")[-1].split(".")[0] + ".docx", 12) doc.Close() successList.append(name) except Exception as e: errorList.append(name) continue writeMsg()
读取Word内容
假如Word的内容为:
代码为:
# coding=UTF-8from docx import Documentimport xlrd#打开word文档document = Document('test.docx')#获取word文档中的所有表格是一个listtempTable = document.tables#获取第一个表格table = tempTable[0]#遍历表格for x in table.rows: for y in x.cells: print y.text, print
则读取如下:
如果把表格合并成如下格式:
读取如下:
可以看出虽然表格合并了,可还是按3行3列输出,只不过是合并的内容相同,这样从Word中取数据就特别麻烦,可以通过判重来取,但也是特别复杂,下面写一个简单的Demo说一下具体的做法
主要思路
主要思路是弄一个模板表用来获取每个字段数据所在的位置,读取模板表将数据放入dict中,其中key为字段名,值为位置,在读取数据表,通过dict获取字段的值,并将字段的值和字段的数据放入sheetdict中,最后将sheetdict和excel列名相同的数据放到这一列下面,我们不能通过api直接在空的excel中写数据,直接通过复制一个空的excel得到另一个excel,在复制的这个excel中写数据
Word和Excel的格式
模板表.docx
学生信息表1.docx
学生信息表.xlsx
样例代码
# _*_ coding:utf-8 _*_from docx import Documentimport xlwtimport xlrdfrom xlutils.copy import copyimport sysimport osreload(sys)sys.setdefaultencoding('utf-8')#开始的excelstartExcel = r'D:\workSpace\forShow\学生信息表.xlsx'#最后生成的excel,这个库只能保存xls格式的文件endExcel = r'D:\workSpace\forShow\学生信息表.xls'#模板表templete = r'D:\workSpace\forShow\模板表.docx'#word所在的文件夹wordDir = r'D:\workSpace\forShow\数据'#模板表中每个字段对应的位置,键是字段,值是所在的位置dict1 = {}#判断是否是英文def isEnglish(checkStr): for ch in checkStr.decode('utf-8'): if u'\u4e00' <= ch <= u'\u9fff': return False return True#读取模板表def readTemplate(): document = Document(templete.decode('utf-8')) tempTable = document.tables table = tempTable[0] rowList = table.rows columnList = table.columns rowLength = len(rowList) columnLength = len(columnList) for rowIndex in range(rowLength): for columnIndex in range(columnLength): cell = table.cell(rowIndex,columnIndex) if isEnglish(cell.text): dict1.setdefault(cell.text,[rowIndex,columnIndex])#读入的表re = xlrd.open_workbook(startExcel.decode("utf-8"))#通过复制读入的表来生成写入的表we = copy(re)#写第一页的sheetdef writeFirstSheet1(table, row): sheet = we.get_sheet(0) #将字段对应的值填到sheet1dict中 sheet1dict = {} for key in dict1: tempList = dict1[key] for index in range(0,1): x = tempList[index] y = tempList[index+1] sheet1dict.setdefault(key,table.cell(x,y).text) #读取第一个sheet tempSheet = re.sheet_by_index(0) #读取第一个sheet中的第二行 list1 = tempSheet.row_values(1) for excelIndex in range(len(list1)): for key in sheet1dict: if list1[excelIndex] == key: #将sheet1dict中的内容写入excel的sheet中 sheet.write(row, excelIndex, sheet1dict[key])#将word中数据写入exceldef writeExcel(wordName, row): document = Document(wordName) tempTable = document.tables table = tempTable[0] #一个excel一般有好几个sheet(即页数),所以单独写一个函数 writeFirstSheet1(table, row) we.save(endExcel.decode("utf-8"))if __name__ == "__main__": readTemplate() docFiles = os.listdir(wordDir.decode("utf-8")) # 开始数据的行数 row = 1 for doc in docFiles: #输出文件名 print doc.decode("utf-8") try: row += 1 writeExcel(wordDir + '\\' + doc.decode("utf-8"), row) except Exception as e: print(e)
生成的Excel
学生信息表.xls
源码地址:http://download.csdn.net/download/zzti_erlie/9953957
参考博客:(第一个为关于python-docx的,剩下的为excel的)
[1]http://www.cnblogs.com/rencm/p/6285304.html
[2]http://www.jb51.net/article/63498.htm
[3]http://blog.csdn.net/wangkai_123456/article/details/50457284
[4]http://www.jb51.net/article/60510.htm
[5]http://www.cnblogs.com/pangwanzi/p/6475871.html
[6]https://www.crifan.com/python_append_new_data_into_existing_excel_xls_file/
- 用Python将Word中的内容写入Excel
- 将excel中的内容写入到PDF中(java)
- 用python将excel数据写入mysql
- 将ListView中的内容导出到Word和Excel
- 将ListView中的内容导出到Word和Excel(新)
- 将ListView中的内容导出到Word和Excel(新)
- python 将数据写入excel
- C#将数据库内容写入Word中
- 将html内容写入word文档
- 用Python读取Word文档并写入Excel(一)
- 用Python读取Word文档并写入Excel(二)
- 将Excel文件内容写入到数据库
- 用Python将较大内容写入文件的注意事项
- python将文件夹里所有的txt文件内容写入excel
- 用Python将数据写入已存在Excel
- word中的内容转到excel中的技巧
- 将文件中的内容写入链表
- js将html中的内容导出word、或者excel文件的方法
- 【算法】数组中出现次数超过一半的数字
- Java技术:Gif编码器(gifencoder)的实际应用(2)
- 斯特林数
- 【转】css中float left与float right的使用说明
- js中apply和Math.max()函数的问题?
- 用Python将Word中的内容写入Excel
- 两个有序链表序列的合并
- Redis-数据结构-跳跃表-skiplist
- spring-boot结合mysql整合mybatis
- 装饰模式
- 天天学Linux命令6--rm 命令
- ACM 1021 Fibonacci Again
- 完整安装vmware10和centOS6.4(64位)
- 对于查询调优,你需要的不止STATISTICS IO