標籤:
匯入
import xlrd
開啟excel
data = xlrd.open_workbook(‘demo.xls‘) #注意這裡的workbook首字母是小寫
查看檔案中包含sheet的名稱
data.sheet_names()
得到第一個工作表,或者通過索引順序 或 工作表名稱
table = data.sheets()[0]
table = data.sheet_by_index(0)
table = data.sheet_by_name(u‘Sheet1‘)
擷取行數和列數
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/
python操作Excel讀寫(使用xlrd和xlrt)