使用Python將Word中的內(nèi)容寫入Excel
下載Python和依賴的庫
python-docx讀取Word的庫
官網(wǎng):http://python-docx.readthedocs.io/en/latest/
讀取Excel的庫:xlrd
寫入Excel的庫:xlwt
兩者的幫助庫:xlutils
官網(wǎng):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文檔,需要轉(zhuǎn)為docx才能被這些庫打開,因此用pywin32把.doc的文件轉(zhuǎn)為.docx的文件,并且把轉(zhuǎn)換的相關(guān)信息寫到一個Excel里面
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')
#要轉(zhuǎn)換的doc文件目錄
docDir = r'C:\Users\Administrator\Desktop\井陘礦區(qū)\井陘礦區(qū)'
#轉(zhuǎn)換成功的docx文件目錄
docxDir = r'D:\data\data10'
#包含轉(zhuǎn)換信息的文件,主要包括轉(zhuǎn)換成功的文件,轉(zhuǎn)換失敗的文件
msgExcel = r'D:\data\data10\轉(zhuǎn)換信息表1.xls'
#文件總數(shù)
fileTotal = 0
#轉(zhuǎn)換正確的文件總數(shù)
successList = []
#裝換錯誤的文件總數(shù)
errorList = []
#將轉(zhuǎn)換信息寫入到excel中
def writeMsg():
excel = xlwt.Workbook(encoding='utf-8')
# 這個是指定sheet頁的名稱
sheet1 = excel.add_sheet('統(tǒng)計信息')
sheet2 = excel.add_sheet('詳細信息')
sheet1.write(0, 0, '文件總數(shù)')
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()
為了轉(zhuǎn)換方便LZ直接封裝了一個工具,你們也可以模仿我這個頁面將自己的工具也封裝成圖形界面:http://blog.csdn.net/zzti_erlie/article/details/78922112
讀取Word內(nèi)容
假如Word的內(nèi)容為:

代碼為:
# 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列輸出,只不過是合并的內(nèi)容相同,這樣從Word中取數(shù)據(jù)就特別麻煩,可以通過判重來取,但也是特別復雜,下面寫一個簡單的Demo說一下具體的做法
主要思路
主要思路是弄一個模板表用來獲取每個字段數(shù)據(jù)所在的位置,讀取模板表將數(shù)據(jù)放入dict中,其中key為字段名,值為位置,在讀取數(shù)據(jù)表,通過dict獲取字段的值,并將字段的值和字段的數(shù)據(jù)放入sheetdict中,最后將sheetdict和excel列名相同的數(shù)據(jù)放到這一列下面,我們不能通過api直接在空的excel中寫數(shù)據(jù),直接通過復制一個空的excel得到另一個excel,在復制的這個excel中寫數(shù)據(jù)
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\數(shù)據(jù)'
#模板表中每個字段對應(yīng)的位置,鍵是字段,值是所在的位置
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)
#將字段對應(yīng)的值填到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中的內(nèi)容寫入excel的sheet中
sheet.write(row, excelIndex, sheet1dict[key])
#將word中數(shù)據(jù)寫入excel
def writeExcel(wordName, row):
document = Document(wordName)
tempTable = document.tables
table = tempTable[0]
#一個excel一般有好幾個sheet(即頁數(shù)),所以單獨寫一個函數(shù)
writeFirstSheet1(table, row)
we.save(endExcel.decode("utf-8"))
if __name__ == "__main__":
readTemplate()
docFiles = os.listdir(wordDir.decode("utf-8"))
# 開始數(shù)據(jù)的行數(shù)
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

知識擴展
使Python把文件夾下所有的excle寫入word文件中
完整代碼
from pathlib import Path, PurePath
from openpyxl import load_workbook
from docx import Document
# 當前目錄
p = Path('./')
# 獲取所有 xlsx 文件
files = [x for x in p.iterdir() if x.is_file() and PurePath(x).match('*.xlsx')]
# 創(chuàng)建 Word 文檔
doc = Document()
for file in files:
print(f'文件名={file.name}')
wb = load_workbook(file)
for sheet_name in wb.sheetnames:
print(f"工作表名稱: {sheet_name}")
ws = wb[sheet_name]
# 在 Word 中加標題(文件名 + sheet名)
doc.add_heading(f"{file.name} - {sheet_name}", level=2)
# 獲取 sheet 所有數(shù)據(jù)
data = []
for row in ws.iter_rows(values_only=True):
# 如果整行都是空,則跳過
if all(cell in (None, '') for cell in row):
continue
data.append([str(cell) if cell is not None else '' for cell in row])
if data:
# 創(chuàng)建 Word 表格
table = doc.add_table(rows=1, cols=len(data[0]))
table.style = 'Table Grid'
# 表頭(假如沒有表頭,這里就只是第一行)
hdr_cells = table.rows[0].cells
for idx, val in enumerate(data[0]):
hdr_cells[idx].text = val
# 添加數(shù)據(jù)行
for row_data in data[1:]:
row_cells = table.add_row().cells
for idx, val in enumerate(row_data):
row_cells[idx].text = val
doc.add_paragraph('') # 分段落空行
else:
doc.add_paragraph('(此工作表為空)')
# 保存 Word 文件
output_dir = Path('../word')
output_dir.mkdir(exist_ok=True, parents=True)
output_file = output_dir / 'merged.docx'
doc.save(output_file)
print(f"已將所有 Excel 數(shù)據(jù)寫入 Word 文件: {output_file}")
到此這篇關(guān)于使用Python將Word中的內(nèi)容寫入Excel的文章就介紹到這了,更多相關(guān)Python Word寫入Excel內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實現(xiàn)將字典(列表按列)存入csv文件
這篇文章主要介紹了Python實現(xiàn)將字典(列表按列)存入csv文件方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06
Python計算標準差之numpy.std和torch.std的區(qū)別
Torch自稱為神經(jīng)網(wǎng)絡(luò)中的numpy,它會將torch產(chǎn)生的tensor放在GPU中加速運算,就像numpy會把array放在CPU中加速運算,下面這篇文章主要給大家介紹了關(guān)于Python?Numpy計算標準差之numpy.std和torch.std區(qū)別的相關(guān)資料,需要的朋友可以參考下2022-08-08
Python使用coloredlogso庫打造彩色日志的全攻略
想象一下,當你的服務(wù)突然報錯時,在一堆灰色文本中快速定位到那個鮮紅的ERROR信息,能節(jié)省多少排查時間?這就是coloredlogs庫的價值所在,下面我們就來看看它的具體使用吧2026-02-02
pybaobabdt庫基于python的決策樹隨機森林可視化工具使用
這篇文章主要為大家介紹了pybaobabdt庫基于python的決策樹隨機森林可視化工具使用探索,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-02-02

