python操做Excel讀寫(使用xlrd和xlrt)

導入python

import xlrd數組

打開excel字體

data = xlrd.open_workbook('demo.xls') #注意這裏的workbook首字母是小寫google

查看文件中包含sheet的名稱spa

data.sheet_names()excel

獲得第一個工做表,或者經過索引順序 或 工做表名稱orm

table = data.sheets()[0]索引

table = data.sheet_by_index(0)ci

table = data.sheet_by_name(u'Sheet1')get

獲取行數和列數

nrows = table.nrows

ncols = table.ncols

獲取整行和整列的值(數組)

table.row_values(i)

table.col_values(i)

循環行,獲得索引的列表

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

簡單的寫入

row = 0

col = 0

ctype = 1 # 類型 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error

value = 'lixiaoluo'

xf = 0 # 擴展的格式化 (默認是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

簡單使用

導入xlwt

import xlwt

新建一個excel文件

file = xlwt.Workbook() #注意這裏的Workbook首字母是大寫,無語吧

新建一個sheet

table = file.add_sheet('sheet name')

寫入數據table.write(行,列,value)

table.write(0,0,'test')

若是對一個單元格重複操做,會引起

returns error:# Exception: Attempt to overwrite cell:# sheetname=u'sheet 1' rowx=0 colx=0

因此在打開時加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() #爲樣式建立字體

font.name = 'Times New Roman'

font.bold = True

style.font = font #爲樣式設置字體

table.write(0, 0, 'some bold Times text', style) # 使用樣式

xlwt 容許單元格或者整行地設置格式。還能夠添加連接以及公式。能夠閱讀源代碼,那裏有例子:

dates.py, 展現如何設置不一樣的數據格式

hyperlinks.py, 展現如何建立超連接 (hint: you need to use a formula)

merged.py, 展現如何合併格子

row_styles.py, 展現如何應用Style到整行格子中.

具體的例子能夠看:

http://scienceoss.com/write-excel-files-with-python-using-xlwt/

google論壇:

http://groups.google.com/group/python-excel/

相關文章
相關標籤/搜索