python win32com模块
今天再次被python的強大所折服,一直很奇怪公司的excel文件直接生成sql腳本是怎么實現(xiàn)的,今天閑著沒事找到實現(xiàn)腳本看了下,竟然就是用python寫的!!!當時真的是震驚了,仔細看了下腳本內(nèi)容,里面用到了一個關鍵模塊win32com,這里在網(wǎng)上找到了一些大神們總結的該模塊用法,碼來一起學習!!
import win32com
?from win32com.client import Dispatch,constants
w =win32com.client.Dispatch('Word.Application')
?# 或者使用下面的方法,使用啟動獨立的進程:
# w = win32com.client.DispatchEx('Word.Application')
# 后臺運行,不顯示,不警告
w.Visible = 0
?w.DisplayAlerts = 0
# 打開新的文件
doc = w.Documents.Open( FileName = filenamein )
?# worddoc = w.Documents.Add() # 創(chuàng)建新的文檔
# 插入文字
myRange = doc.Range(0,0)
?myRange.InsertBefore('Hello fromPython!')
# 使用樣式
wordSel = myRange.Select()
?wordSel.Style = constants.wdStyleHeading1
# 正文文字替換
w.Selection.Find.ClearFormatting()
?w.Selection.Find.Replacement.ClearFormatting()
?w.Selection.Find.Execute(OldStr, False,False, False, False, False, True, 1, True, NewStr, 2)
# 頁眉文字替換
w.ActiveDocument.Sections[0].Headers[0].Range.Find.ClearFormatting()
?w.ActiveDocument.Sections[0].Headers[0].Range.Find.Replacement.ClearFormatting()
?w.ActiveDocument.Sections[0].Headers[0].Range.Find.Execute(OldStr,False, False, False, False, False, True, 1, False, NewStr, 2)
# 表格操作
doc.Tables[0].Rows[0].Cells[0].Range.Text ='123123'
?worddoc.Tables[0].Rows.Add() # 增加一行
# 轉(zhuǎn)換為html
?wc = win32com.client.constants
?w.ActiveDocument.WebOptions.RelyOnCSS =1
?w.ActiveDocument.WebOptions.OptimizeForBrowser= 1
?w.ActiveDocument.WebOptions.BrowserLevel= 0 # constants.wdBrowserLevelV4
?w.ActiveDocument.WebOptions.OrganizeInFolder =0
?w.ActiveDocument.WebOptions.UseLongFileNames =1
?w.ActiveDocument.WebOptions.RelyOnVML =0
?w.ActiveDocument.WebOptions.AllowPNG = 1
?w.ActiveDocument.SaveAs( FileName =filenameout, FileFormat = wc.wdFormatHTML )
# 打印
doc.PrintOut()
# 關閉
# doc.Close()
?w.Documents.Close(wc.wdDoNotSaveChanges)
?w.Quit()
(3)處理excel
[1]使用PyExcelerator讀寫EXCEL文件(Platform: Win,Unix-like)
優(yōu)點:簡單易用????? 缺點:不可改變已存在的EXCEL文件。
PyExcelerator是一個開源的MS Excel文件處理python包。它主要是用來寫 Excel 文件.URL:?http://sourceforge.net/projects/pyexcelerator/
我沒有找到關于PyExcelerator的文檔。只是看到了limodou的一篇介紹。
http://blog.donews.com/limodou/archive/2005/07/09/460033.aspx
這個包使用起來還是比較簡單的:)。帶了很多小例子,可以參照。
例mini.py.
=================================
#!/usr/bin/env python
# -*- coding:windows-1251 -*-
# Copyright (C) 2005Kiseliov Roman
__rev_id__ ="""$Id: mini.py,v 1.3 2005/03/27 12:47:06 rvk Exp$"""
"導入模塊
from pyExceleratorimport *
"生成一個工作薄
w = Workbook()
"加入一個Sheet
ws = w.add_sheet('Hey,Dude')
"保存
w.save('mini.xls')
=================================
[2]使用COM接口,直接操作EXCEL(只能在Win上)
優(yōu)點:可以滿足絕大數(shù)要求。缺點:有些麻煩。:-)
這方面的例子很多,GOOGLE 看吧:-). 文檔也可以參看OFFICE自帶的VBA EXCEL 幫助文件(VBAXL.CHM)。這里面講述了EXCEL VBA的編程概念,
不錯的教程!另外,《Python Programming on Win32》書中也有很詳細的介紹。這本書中給出了一個類來操作EXCEL 文件,可以很容易的加以擴展。
#!/usr/bin/env python
# -*- coding: utf-8-*-
from win32com.clientimport Dispatch
importwin32com.client
class easyExcel:
??? """A utility to make iteasier to get at Excel.? Remembering
??? to save the data is your problem, asis? error handling.
??? Operates on one workbook at atime."""
??? def __init__(self, filename=None):
??????? self.xlApp =win32com.client.Dispatch('Excel.Application')
??????? if filename:
??????????? self.filename = filename
??????????? self.xlBook =self.xlApp.Workbooks.Open(filename)
??????? else:
??????????? self.xlBook =self.xlApp.Workbooks.Add()
??????????? self.filename = ''?
??? def save(self, newfilename=None):
??????? if newfilename:
??????????? self.filename = newfilename
??????????? self.xlBook.SaveAs(newfilename)
??????? else:
??????????? self.xlBook.Save()???
??? def close(self):
??????? self.xlBook.Close(SaveChanges=0)
??????? del self.xlApp
??? def getCell(self, sheet, row, col):
??????? "Get value of one cell"
??????? sht = self.xlBook.Worksheets(sheet)
??????? return sht.Cells(row, col).Value
??? def setCell(self, sheet, row, col, value):
??????? "set value of one cell"
??????? sht = self.xlBook.Worksheets(sheet)
??????? sht.Cells(row, col).Value = value
??? def getRange(self, sheet, row1, col1, row2,col2):
??????? "return a 2d array (i.e. tuple oftuples)"
??????? sht = self.xlBook.Worksheets(sheet)
??????? return sht.Range(sht.Cells(row1, col1),sht.Cells(row2, col2)).Value
?? ?defaddPicture(self, sheet, pictureName, Left, Top, Width, Height):
??????? "Insert a picture in sheet"
??????? sht = self.xlBook.Worksheets(sheet)
??????? sht.Shapes.AddPicture(pictureName, 1,1, Left, Top, Width, Height)
??? def cpSheet(self, before):
??????? "copy sheet"
??????? shts = self.xlBook.Worksheets
??????? shts(1).Copy(None,shts(1))
"下面是一些測試代碼。
if __name__ =="__main__":
??? PNFILE = r'c:\screenshot.bmp'
??? xls = easyExcel(r'D:\test.xls')
??? xls.addPicture('Sheet1', PNFILE, 20,20,1000,1000)
??? xls.cpSheet('Sheet1')
??? xls.save()
??? xls.close()
(4)python調(diào)用短信貓控件,發(fā)短信
#! /usr/bin/env python
#coding=gbk
import sys
import win32com.client
ocxname='ShouYan_SmsGate61.Smsgate'
axocx=win32com.client.Dispatch(ocxname)
axocx.CommPort=8#設置COM端口號
axocx.SmsService='+8613800100500'#設置短信服務號碼
axocx.Settings='9600,n,8,1'#設置com端口速度
axocx.sn='loyin'
c=axocx.Connect(1)#連接短信貓或手機
?
print '連接情況',axocx.Link()
?
axocx.SendSms('python確實是很好的','15101021000',0)#發(fā)送短信
總結
以上是生活随笔為你收集整理的python win32com模块的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Android 应用开发】Activi
- 下一篇: 新书品读《三级网络技术预测试卷与考点解析