用Python将Word中的内容写入Excel
2017-08-27 13:06
2126 查看
下载Python和依赖的库
python-docx读取Word的库官网:http://python-docx.readthedocs.io/en/latest/
读取Excel的库:xlrd
写入Excel的库:xlwt
两者的帮助库:xlutils
官网:http://www.python-excel.org/
上面是操作xls文件的库,如果要操作xlsx文件可以用openpyxl这个库
在命令行中输入以下命令即可
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
xlrd,xlwt,xlutils只能操作xls类型的文件,如果想要操作xlsx类型的文件,可以用openpyxl这个库
如果需要直接修改一下输入和输出目录
# _*_ coding:utf-8 _*_ import os import win32com import xlwt from win32com.client import Dispatch import sys reload(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()
为了转换方便LZ直接封装了一个工具,你们也可以模仿我这个页面将自己的工具也封装成图形界面:http://blog.csdn.net/zzti_erlie/article/details/78922112
读取Word内容
假如Word的内容为:代码为:
# coding=UTF-8 from docx import Document import xlrd #打开word文档 document = Document('test.docx') #获取word文档中的所有表格是一个list tempTable = 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 Document import xlwt import xlrd from xlutils.copy import copy import sys import os reload(sys) sys.setdefaultencoding('utf-8') #开始的excel startExcel = 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) #写第一页的sheet def 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中数据写入excel def 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读取txt内容写入xls格式的excel中
- 【Python小工具】Python实现批量解析PDF文件提取内容并写入到Excel中
- Python读取txt内容写入xlsx格式的excel中
- 用Python读取Word文档并写入Excel(二)
- python数据清理——将excel单元格的内容写入到txt
- Python写入excel提示“excel中有不可读的内容”
- Python读取txt内容写入xls格式excel中的方法
- 用Python读取Word文档并写入Excel(一)
- python 将txt内容写入excel
- python将文件夹里所有的txt文件内容写入excel
- XCLNetFileReplace(文件名文件内容批量替换工具),支持Word/Excel/文本文件(无需安装office)
- 【原创】上传EXCEL并把内容批量写入指定数据库
- Java程序员从笨鸟到菜鸟之(一百零三)java操作office和pdf文件(一)java读取word,excel和pdf文档内容
- Python 3从入门到精通12-创建新文件并写入内容,在文件尾部更新内容
- 将Excel文件内容写入到数据库
- JavaScript将Web页面内容导出到Word及Excel的方法
- Python对excel写入数据操作实例代码(只供参考)
- python 将百度搜索风云榜的关键内容提取并写入txt文件和读取验证
- 将excel中的内容写入到PDF中(java)
- C# 创建Excel并写入内容