1. 程式人生 > >Python xlrd、xlwt、xlutils修改Excel檔案

Python xlrd、xlwt、xlutils修改Excel檔案

基本部分

在寫入Excel表格之前,你必須初始化workbook物件,然後新增一個workbook物件。比如:
import xlwt
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('sheet 1')

這樣表單就被建立了,寫入資料也很簡單:
# indexing is zero based, row then column
sheet.write(0,1,'test text')

之後,就可以儲存檔案(這裡不需要想開啟檔案一樣需要close檔案):
wbk.save('test.xls')

深入探索

worksheet物件,當你更改表單內容的時候,會有警告提示。
sheet.write(0,0,'test')
sheet.write(0,0,'oops')
 
# returns error:
# Exception: Attempt to overwrite cell:
# sheetname=u'sheet 1' rowx=0 colx=0

解決方式:使用cell_overwrite_ok=True來建立worksheet:
sheet2 =  wbk.add_sheet('sheet 2', cell_overwrite_ok=True)
sheet2.write(0,0,'some text')
sheet2.write(0,0,'this should overwrite')

這樣你就可以更改表單2的內容了。

更多
# Initialize a style
style = xlwt.XFStyle()
 
# Create a font to use with the style
font = xlwt.Font()
font.name = 'Times New Roman'
font.bold = True
 
# Set the style's font to this new one you set up
style.font = font
 
# Use the style when writing
sheet.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到整行格子中.