傳說(shuō)中python操作ms office功能最強(qiáng)大的是win32com(據(jù)說(shuō)只要人工能操作的它都能實(shí)現(xiàn),未嘗試尚不知道真假),不過(guò)對(duì)于比較簡(jiǎn)單的需求顯得有些小題大作。那么來(lái)看下簡(jiǎn)單的,分別是xlrd和xlwt模塊。
xlrd
http://pypi.python.org/pypi/xlrd
簡(jiǎn)單使用
導(dǎo)入
import xlrd
打開(kāi)excel
data = xlrd.open_workbook('demo.xls') #注意這里的workbook首字母是小寫(xiě)
查看文件中包含sheet的名稱
data.sheet_names()
得到第一個(gè)工作表,或者通過(guò)索引順序 或 工作表名稱
table = data.sheets()[0]
table = data.sheet_by_index(0)
table = data.sheet_by_name(u'Sheet1')
獲取行數(shù)和列數(shù)
nrows = table.nrows
ncols = table.ncols
獲取整行和整列的值(數(shù)組)
table.row_values(i)
table.col_values(i)
循環(huán)行,得到索引的列表
for rownum in range(table.nrows):
print table.row_values(rownum)
單元格
cell_A1 = table.cell(0,0).value
cell_C4 = table.cell(2,3).value
分別使用行列索引
cell_A1 = table.row(0)[0].value
cell_A2 = table.col(1)[0].value
簡(jiǎn)單的寫(xiě)入
row = 0
col = 0
ctype = 1 # 類型 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
value = 'lixiaoluo'
xf = 0 # 擴(kuò)展的格式化 (默認(rèn)是0)
table.put_cell(row, col, ctype, value, xf)
table.cell(0,0) # 文本:u'lixiaoluo'
table.cell(0,0).value # 'lixiaoluo'
xlwt
http://pypi.python.org/pypi/xlrd
簡(jiǎn)單使用
導(dǎo)入xlwt
import xlwt
新建一個(gè)excel文件
file = xlwt.Workbook() #注意這里的Workbook首字母是大寫(xiě),無(wú)語(yǔ)吧
新建一個(gè)sheet
table = file.add_sheet('sheet name')
寫(xiě)入數(shù)據(jù)table.write(行,列,value)
table.write(0,0,'test')
如果對(duì)一個(gè)單元格重復(fù)操作,會(huì)引發(fā)
returns error:
# Exception: Attempt to overwrite cell:
# sheetname=u'sheet 1' rowx=0 colx=0
所以在打開(kāi)時(shí)加cell_overwrite_ok=True解決
table = file.add_sheet('sheet name',cell_overwrite_ok=True)
保存文件
file.save('demo.xls')
另外,使用style
style = xlwt.XFStyle() #初始化樣式
font = xlwt.Font() #為樣式創(chuàng)建字體
font.name = 'Times New Roman'
font.bold = True
style.font = font #為樣式設(shè)置字體
table.write(0, 0, 'some bold Times text', style) # 使用樣式
xlwt 允許單元格或者整行地設(shè)置格式。還可以添加鏈接以及公式??梢蚤喿x源代碼,那里有例子:
dates.py, 展示如何設(shè)置不同的數(shù)據(jù)格式
hyperlinks.py, 展示如何創(chuàng)建超鏈接 (hint: you need to use a formula)
merged.py, 展示如何合并格子
row_styles.py, 展示如何應(yīng)用Style到整行格子中.
具體的例子可以看:
http://scienceoss.com/write-excel-files-with-python-using-xlwt/
google論壇:
http://groups.google.com/group/python-excel/