1. 程式人生 > >python讀取excel匯入word表格

python讀取excel匯入word表格

# -*- coding: utf-8 -*-
from openpyxl import load_workbook
from docx import Document
import time
import sys
import os

reload(sys)
sys.setdefaultencoding('utf8')
# 開始時間
startTime = time.time()

# 讀取excel2007檔案
wb = load_workbook(filename=r'1.xlsx')

# word文件
document = Document()

document.add_heading('Document Title'
, 0) table = document.add_table(rows=1, cols=7) hdr_cells = table.rows[0].cells hdr_cells[0].text = u'測試用例編號' hdr_cells[1].text = u'測試用例名稱' hdr_cells[2].text = u'測試用例標題' hdr_cells[3].text = u'預置條件' hdr_cells[4].text = u'操作步驟' hdr_cells[5].text = u'預期結果' hdr_cells[6].text = u'實際結果' # 取第三張表 sheetnames = wb.get_sheet_names() ws = wb.get_sheet_by_name(sheetnames[2
]) i = 1 # 寫入word for row in ws.rows: if type(row[2].value) is long: row_cells = table.add_row().cells row_cells[0].text = u'' + str(i) i = i + 1 row_cells[1].text = u'QYWEB_' + str(row[2].value).zfill(2) + u".py" row_cells[2].text = u'' + str(row[3].value) row_cells[3
].text = u'' + str(row[6].value) row_cells[4].text = u'' + str(row[7].value) row_cells[5].text = u'' + str(row[8].value) row_cells[6].text = u'成功' document.add_page_break() document.save('demo.docx')

需要注意中文編碼問題,特此記錄。