python读取word文档中的数据保存为excel_使用python读取多重文件夹下的word(doc、docx)文件,并处理存储到excel(xls、xlsx)文件...

#-*- coding:gbk -*-

importosimportdocxfrom win32com importclient as wcimportxlwtimportxlsxwriter#获取filepath文件夹下的所有的文件

defgetfilelist(filepath):

filelist=os.listdir(filepath)

files=[]for i inrange(len(filelist)):

child= os.path.join('%s\\%s' %(filepath, filelist[i]))ifos.path.isdir(child):

files.extend(getfilelist(child))else:

files.append(child)returnfiles#获取word文件文本

defgetDocx(fileName):

d=docx.opendocx(fileName)

doc=docx.getdocumenttext(d)returndoc#将doc转换为docx

defdoc2Docx(fileName):

word= wc.Dispatch("Word.Application")

doc=word.Documents.Open(fileName)

doc.SaveAs(fileName+ "x", 12, False, "", True, "", False, False, False, False)

os.remove(fileName)

doc.Close()

word.Quit()

filepath= "C:\\xxx\\xx\\xx\\xx\\数据集"filelist=(getfilelist(filepath))##如果文件夹下的文件都是doc,需要先通过该函数全部转变为docx##for i in range(len(filelist)):## doc2Docx(filelist[i])

list=[]for i inrange(len(filelist)):if (filelist[i].endswith("docx")):

list.append(filelist[i])#使用xlwt写入到excel,当存在大文本的时候会出现错误:Exception: String longer than 32767 characters##for i in range(len(list)):## fileName = list[i]## doc = get_docx(fileName)## filePaths = fileName.split("\\")## string = ""## for j in range(len(doc)):## string += doc[j] + "\n"## if (len(string) > 10000):## string = string[:10000]## filePaths.append(string)## for j in range(20, -1, -1):## if j < len(filePaths):## worksheet.write(i, j, label = filePaths[j])##workbook.save('Excel_Workbook.xls')

#使用xlsxwriter处理超过的32767word文本

workbook = xlsxwriter.Workbook(u'数据.xlsx')

worksheet= workbook.add_worksheet(u"数据")for i inrange(len(list)):

fileName=list[i]

doc=get_docx(fileName)

filePaths= fileName.split("\\")

string= ""

for j inrange(len(doc)):

string+= doc[j] + "\n"filePaths.append(string)for j in range(20, -1, -1):if j

worksheet.write(i, j, filePaths[j])

workbook.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值