Python for win

Python操作Excel方法:


(1)在sourceforge.net上有一个扩展模块叫pyXLWriter,可以方便的写Excel文件。
(2)下载win32com包装上,这个包可以调用windows的com及API函数等这类的功能。Python利用win32com操作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 Programming on Win32》

 

一个用Python对win操作的网站:
http://win32com.goermezer.de/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值