python Excel 編程1)Excel hyperlink:
xlsApp = win32com.client.Dispatch('Excel.Application')
cell = xls.App.ActiveSheet.Cells(1,1)
cell.Hyperlink.Add(cell,'http://xxx')
2)Excel row/column count:
sht = xlsApp.ActiveSheet
sht.Columns.Areas.Count
sht.Rows.Areas.Count
*************************
[1]使用PyExcelerator讀寫EXCEL檔案(Platform: Win,Unix-like)
優點:簡單易用 缺點:不可改變已存在的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) 2005 Kiseliov Roman
__rev_id__ = """$Id: mini.py,v 1.3 2005/03/27 12:47:06 rvk Exp $"""
"匯入模組
from pyExcelerator import *
"產生一個工作薄
w = Workbook()
"加入一個Sheet
ws = w.add_sheet('Hey, Dude')
"儲存
w.save('mini.xls')
=================================
[2]使用COM介面,直接操作EXCEL(只能在Win上)
優點:可以滿足絕大數要求。缺點:有些麻煩。:-)
這方面的例子很多,GOOGLE 看吧:-). 文檔也可以參看OFFICE內建的VBA EXCEL 協助檔案(VBAXL.CHM)。這裡面講述了EXCEL VBA的編程概念,
不錯的教程!另外,《Python Programming on Win32》書中也有很詳細的介紹。這本書中給出了一個類來操作EXCEL 檔案,可以很容易的加以擴充。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from win32com.client import Dispatch
import win32com.client
class easyExcel:
"""A utility to make it easier to get at Excel. Remembering
to save the data is your problem, as is error handling.
Operates on one workbook at a time."""
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 of tuples)"
sht = self.xlBook.Worksheets(sheet)
return sht.Range(sht.Cells(row1, col1), sht.Cells(row2, col2)).Value
def addPicture(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()
******************************************************************************
python Word 編程
http://doc.zoomquiet.org/data/20051227094903/
import win32comfrom win32com.client import Dispatch, constantsw = win32com.client.Dispatch('Word.Application')# 或者使用下面的方法,使用啟動獨立的進程:# w = win32com.client.DispatchEx('Word.Application')# 後台運行,不顯示,不警告w.Visible = 0w.DisplayAlerts = 0# 開啟新的檔案doc = w.Documents.Open( FileName = filenamein )# worddoc = w.Documents.Add() # 建立新的文檔# 插入文字myRange = doc.Range(0,0)myRange.InsertBefore('Hello from Python!')# 使用樣式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() # 增加一行# 轉換為htmlwc = win32com.client.constantsw.ActiveDocument.WebOptions.RelyOnCSS = 1w.ActiveDocument.WebOptions.OptimizeForBrowser = 1w.ActiveDocument.WebOptions.BrowserLevel = 0 # constants.wdBrowserLevelV4w.ActiveDocument.WebOptions.OrganizeInFolder = 0w.ActiveDocument.WebOptions.UseLongFileNames = 1w.ActiveDocument.WebOptions.RelyOnVML = 0w.ActiveDocument.WebOptions.AllowPNG = 1w.ActiveDocument.SaveAs( FileName = filenameout, FileFormat = wc.wdFormatHTML )# 列印doc.PrintOut()# 關閉# doc.Close()w.Documents.Close(wc.wdDoNotSaveChanges)w.Quit()
**************************************************
python ACCESS編程http://xinyu.blogbus.com/s46076/ 因為使用的第三方組件用到python,所以需要瞭解python的資料庫操作。 後來找到了方法,寫了如下的sample: import win32com.client def db1(): print "Start db1." try: conn = win32com.client.Dispatch(r'ADODB.Connection') conn.Open('Provider=SQLOLEDB.1;Password=123456;Persist Security Info=True;User ID=sa;Initial Catalog=ECI-SERVICE;Data Source=10.240.4.135') rs = win32com.client.Dispatch(r'ADODB.Recordset') rs.Cursorlocation=3 rs.Open('select * from EBP_B_AS_ALERT',conn) rs.MoveFirst() for x in range(rs.RecordCount): if rs.EOF: print "End of records" break else: print rs.Fields.Item(1).Value rs.MoveNext() rs.Close() conn.Close() except: print "Except, now." 用的是win32com 的extension。Python2.2.3 自身不帶win32 extension,需要安裝win32all-162(win extensions).exe。 代碼比較簡單,可惜沒有找到api,所以提供哪些方法只能在網上找。 |
|