用Python将Word中的内容写入Excel

下载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

封装图形界面参考

https://github.com/erlieStar/doc2docx

参考博客

第一个为关于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/

  • 10
    点赞
  • 86
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
可以使用Python的docx和openpyxl库来实现从Word文档读取内容写入Excel文件。 首先,需要安装docx和openpyxl库。可以使用以下命令进行安装: ``` pip install python-docx openpyxl ``` 接下来,可以使用以下代码读取Word文档内容: ```python import docx # 打开Word文档 doc = docx.Document('example.docx') # 遍历文档的段落 for para in doc.paragraphs: # 打印每个段落的内容 print(para.text) # 遍历文档表格 for table in doc.tables: # 遍历表格的行 for row in table.rows: # 遍历行的单元格 for cell in row.cells: # 打印每个单元格的内容 print(cell.text) ``` 接下来,可以使用以下代码将读取内容写入Excel文件: ```python import docx from openpyxl import Workbook # 打开Word文档 doc = docx.Document('example.docx') # 创建Excel文件 wb = Workbook() ws = wb.active # 遍历文档的段落 for para in doc.paragraphs: # 将每个段落的内容写入Excel文件 ws.append([para.text]) # 遍历文档表格 for table in doc.tables: # 遍历表格的行 for row in table.rows: # 创建一个空列表用于存储行的单元格内容 row_data = [] # 遍历行的单元格 for cell in row.cells: # 将每个单元格的内容添加到列表 row_data.append(cell.text) # 将列表内容写入Excel文件 ws.append(row_data) # 保存Excel文件 wb.save('example.xlsx') ``` 以上代码将文档的每个段落作为一行写入Excel文件,将表格的每个单元格作为一列写入Excel文件。可以根据需要进行修改。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java识堂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值