本文实例讲述了Python使用win32 COM实现Excel的写入与保存功能。分享给大家供大家参考,具体如下:
本文实例讲述了Python使用win32com模块实现数据库表结构自动生成word表格的方法。分享给大家供大家参考,具体如下:
很久之前通过东拼西凑实现过使用Python通过win32 COM实现word文档的批量处理,后来那段程序功能在我的工作以及生活中被我使用了好多次。在批量处理的时候,不过是一个读写的过程,而读写过后还需保存。类比到Excel的操作中,自然也需要一个保存退出的动作。
下载win32模块
我搜索了自己手头获得的只有几页的文档,没有相应的功能介绍,我也找不到程序的操作方式。只好借着自己的兴趣猜测尝试一下,仿照的自然是word文档的处理。还真让我猜出来了,具体的示例代码如下:
下载链接:https://sourceforge.net/projects/pywin32/files/pywin32/
#!/usr/bin/python
from win32com.client import Dispatch
import os
pwd = os.getcwd()
xlApp = Dispatch('Excel.Application')
xlApp.Visible = True
xlBook = xlApp.Workbooks.Add()
xlApp.Worksheets.Add().Name = 'test'
xlSheet = xlApp.Worksheets('test')
xlSheet.Cells(1,1).Value = 'title'
xlSheet.Cells(2,1).Value = 123
xlBook.SaveAs(pwd '\demo.xlsx')
xlApp.Quit() # exit app
连接mysql
运行程序,Excel的界面会一闪而过。之后在当前文件夹中会出现一个名为demo.xlsx的文件。文件打开后的内容如下:
import MySQLdb
db_host = ""
db_port = 3306
db_name = ""
db_user = ""
db_pwd = ""
db = MySQLdb.connect(host=db_host,port=db_port,user=db_user,passwd=db_pwd,db=db_name,charset="utf8")
cursor = db.cursor()
获取所有表结构
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python操作Excel表格技巧总结》、《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
#获取表数据库中所有表和备注
def get_tables(cursor,db_name):
sql = "select table_name,table_comment from information_schema.tables where table_schema = '" db_name "'"
cursor.execute(sql)
result = cursor.fetchall()
tables = {}
for r in result:
tables[r[0]] = r[1]
return tables
#获取表结构
def get_table_desc(cursor,db_name,table_name):
sql = "select column_name,column_type,column_default,is_nullable,column_comment from information_schema.columns where table_schema = '" db_name "' and table_name = '" table_name "'"
cursor.execute(sql)
result = cursor.fetchall()
return result
本文由wns9778.com发布于计算机教程,转载请注明出处:Python使用win32 COM实现Excel的写入与保存功能示例
关键词: wns9778.com