from win32com.client import Dispatch
xlApp = Dispatch("Excel.Application")
xlApp.Visible = 1
# Check if any workbook exists.
if xlApp.Workbooks.Count == 0:
# If not, create a new one.
workbook = xlApp.Workbooks.Add()
else:
# If yes, use the first one.
workbook = xlApp.Workbooks[0]
# Check if any sheet exists.
if workbook.Sheets.Count == 0:
# If not, add a sheet to current workbook.
sheet = workbook.Sheets.Add()
else:
# If yes, use the first sheet of current workbook.
sheet = workbook.Sheets[0]
# Generate the multiplication table(9x9).
for i in xrange(2, 10):
# Cells(<column>, <row>)
sheet.Cells(1, i).Value = i
sheet.Cells(1, i).Font.Color = 0xFF0000
sheet.Cells(i, 1).Value = i
sheet.Cells(i, 1).Font.Color = 0x00FF00
def a2i(ch):
return ord(ch.upper()) - ord('A') + 1
def i2a(i):
return chr((i-1) + ord('A'))
for i in xrange(2, 10):
for j in xrange(2, 10):
# Generate the Excel formula.
sheet.Cells(i, j).Formula = '=%s1*A%s' % (i2a(j), i)
sheet.Cells(i, j).Font.Color = 0x000000
sheet.Name = "Multiplication Table"
workbook.SaveAs('xxx.xls')
xlApp.Quit()
上面代码可以正确运行。
了解更多参考下面内容:
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: est.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 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() # 创建新的文档
# 插入文字
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() # 增加一行
# 转换为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()
===============
>>> import win32com.client
#指定是应用程序是Excel.Application并得到cel.Application")对象
>>> xlsApp=win32com.client.Dispatch("Excel.Application")
#得到Workbooks
>>> xlsBook=xlsApp.Workbooks.Open("c:\test.xls")
#得到名称为sheet1的Sheet对象
>>> xlsSheet=xlsBook.Sheets("sheet1")
#或者根据索引值获取Sheet对象
xlsSheet=xlsBook.Sheets[0]
#得到有数据的行,这里要注意UsedRange的使用,不使用它也可以但是你会得到所有的整个sheet的单元格了,不是我们需要的。
#这里浪费了我很多时间,由于此前我并没写过类似宏的东东。
>>> rs=xlsSheet.UsedRange.Rows
#最后当然类似读数组那样把它读取出来,具体如何使用我想就看个人什么用途以及喜好了。这里只是打印出来看看
>>> for r in rs:
print r #遍历输出每行
>>> for r in rs:
for onecell in r:
print onecell
print ' '#遍历输出每个单元格,以换行符结束一行