標籤:style http 使用 io 檔案 資料 for 代碼
python操作excel除了讀就是寫。
1 從讀開始 xlrd :http://pypi.python.org/pypi/xlrd
匯入:import xlrd
開啟excel: file = xlrd.open_workbook(‘demo.xls‘)
查看檔案中包含sheet的名稱:file.sheet_names()
得到第一個工作表,或者通過索引順序 或 工作表名稱
sheet = file.sheets()[0]
sheet = file.sheet_by_index(0)
sheet = file.sheet_by_name(u‘Sheet1‘)
擷取行數和列數
nrows = sheet.nrows
ncols = sheet.ncols
迴圈行,得到索引的列表
for rownum in range(sheet.nrows):
print sheet.row_values(rownum)
擷取整行和整列的值(數組)
sheet.row_values(i)
sheet.col_values(i)
儲存格(索引擷取)
cell_A1 = sheet.cell(0,0).value
cell_C4 = sheet.cell(2,3).value
分別使用行列索引
cell_A1 = sheet.row(0)[0].value
cell_A2 = sheet.col(1)[0].value
2 寫 xlwt :http://pypi.python.org/pypi/xlrd
匯入xlwt import xlwt
建立一個excel檔案
file = xlwt.Workbook() #注意這裡的Workbook首字母是大寫,無語吧
建立一個sheet
sheet = file.add_sheet(‘sheet name‘)
寫入資料sheet.write(行,列,value)
sheet.write(0,0,‘test‘)
如果對一個儲存格重複操作,會引發
returns error:
# Exception: Attempt to overwrite cell:
# sheetname=u‘sheet 1‘ rowx=0 colx=0
所以在開啟時加cell_overwrite_ok=True解決
sheet = 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 #為樣式設定字型
sheet.write(0, 0, ‘some bold Times text‘, style) # 使用樣式
xlwt 允許儲存格或者整行地設定格式。還可以添加連結以及公式。
原始碼中的模組:
dates.py, 展示如何設定不同的資料格式
hyperlinks.py, 展示如何建立超連結
merged.py, 展示如何合并格子
row_styles.py, 展示如何應用Style到整行格子中.