程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Developing Excel to word tool with Python

編輯:Python

Python Realization excel turn Word Tool development code implementation , as follows :

import os
import xlrd
import datetime
import time
from mailmerge import MailMerge
def remvocePiont(str):
index = str.find(".")
return str[0:index]
print("------------WORD Save the path -------------------")
print(" After successful conversion WORD The file is kept in :" + r"D:\temp")
print("-------------------------------")
path = input(" Please enter excel File path + file name ( Such as :D:\Desktop\data.xlsx):")
xl = xlrd.open_workbook(path)
print(" Start conversion , One moment please ······ ")
# Read the first table 
table = xl.sheet_by_name(xl.sheet_names()[0])
# Get the number of rows in the table 
nrows = table.nrows
# Generate Word Document storage directory 
path_base_name = r'D:\temp'
for i in range(nrows): # Print line by line 
if i > 0:
template_path = "resource/template.docx"
doc = MailMerge(template_path) # Open template file 
# print(doc.get_merge_fields())
serial = remvocePiont(str(table.row_values(i)[0]))
phone=remvocePiont(str(table.row_values(i)[7]))
address = str(table.row_values(i)[2])
username = str(table.row_values(i)[1]).strip()
linkuser = str(table.row_values(i)[6]).strip()
num = remvocePiont(str(table.row_values(i)[3]))
model = str(table.row_values(i)[4]).strip()
serialNumber = str(table.row_values(i)[5]).strip()
# The following is the corresponding field in the filling template ,
doc.merge(serial=serial,
username=username,
linkuser=linkuser,
address=address,
linkphone=phone,
model=model,
num=num,
serialNumber=serialNumber
)
# Use filename Date name 
path_name = os.path.join(path_base_name,datetime.datetime.now().strftime("%Y-%m-%d"))
if not os.path.exists(path_name):
os.makedirs(path_name)
word_name = path_name +"\\"+ serial +"_"+ username + '.docx'
doc.write(word_name)
doc.close()
print(" Conversion success ,WORD The file is kept in :" + r"D:\temp")
time.sleep(5)

excel The file format is as follows :

word The template is as follows :

word Where the template is all red , according to word Domain set , Use WPS, Insert -> File parts -> Domain , Select Mail Merge , In the domain code MERGEFIELD Add parameter name after ( Corresponding to the code ): Such as serial


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved