python 使用win32com 操作excel

2017-01-13 10:52:14来源:http://hunkz.blog.51cto.com/6157447/1891443作者:独弹古调人点击


举例1

import win32com.client as win32

xl = win32.Dispatch('Excel.Application')xl.Visible = Truexl.Workbooks.Add()

xlBook = xl.Workbooks(1)xlSheet = xl.Sheets(1)xlSheet.Cells(1,1).Value = 'What shall be the number of thy counting?'xlSheet.Cells(2,1).Value = 3print xlSheet.Cells(1,1).Valueprint xlSheet.Cells(2,1).Value

举例2

#coding:utf-8import win32com.client as win32import timeimport pythoncomnow = time.time()print now time_object = pythoncom.MakeTime(now)print int(time_object)xl = win32.Dispatch('Excel.Application')xl.Visible = Truexl.Workbooks.Add()xlBook = xl.Workbooks(1)xlSheet = xl.Sheets(1)xlSheet.Cells(1,1).Value = 'What shall be the number of thy counting?'xlSheet.Cells(2,1).Value = 3#print xlSheet.Cells(2,1).ValuexlSheet.Cells(3,1).Value = time_object#print xlSheet.Cells(3,1).ValuexlSheet.Cells(4,1).Formula = '=A2*2'#print xlSheet.Cells(4,1).Value#print xlSheet.Cells(4,1).FormulaxlSheet.Cells(1,1).Value = None#print xlSheet.Cells(1,1).ValuemyRange1 = xlSheet.Cells(4,1) #一个单元格myRange2 = xlSheet.Range("B5:C10") #myRange3 = xlSheet.Range(xlSheet.Cells(2,2), xlSheet.Cells(3,8))

举例3

class easyExcel: """A utility to make it easier to get at Excel. Remebering 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 sace(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 set(self, sheet, row, col, value): "Set value of one cell" sht = self.xlBook.Worksheets(sheet) sht.Cells(row, col).Value = value


最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台