Python实现mysql数据输出到word表格中(源码)

# -*- coding: utf-8 -*- 
import os,sys,win32com
import MySQLdb,datetime
import win32com.client


reload(sys)
sys.setdefaultencoding('utf-8')




conn= MySQLdb.connect(host='localhost',user='root',passwd='111111',db='gpon',charset='utf8')
cursor= conn.cursor()
getstr="select noid,address,bossnum from xinyi group by noid"
cursor.execute(getstr)
rs=cursor.fetchall()


ks=[]
ks=[[int(i[0]),str(i[1]),int(i[2])] for i in rs]
t=0


for r in ks:
    WordApp = win32com.client.Dispatch("Word.Application")
    WordApp.Visible = True
    doc = WordApp.Documents.Open(r"d:\demo.doc")


    ts = doc.Tables
    ts[0].Cell(2,4).Range.Text=r[2]
    ts[0].Cell(4,2).Range.Text=r[1].encode('gb2312')


    t+=1
    doc.SaveAs(r"d:\boss\%s.doc"%str(r[2]))
    doc.PrintOut()
    doc.Close(-1)


cursor.close()
conn.close()



你可能感兴趣的:(python,mysql,windows)