一、讀取excel
這里介紹一個不錯的包xlrs,可以工作在任何平臺。這也就意味著你可以在Linux下讀取Excel文件。
首先,打開workbook;
代碼如下:
import xlrd
wb = xlrd.open_workbook('myworkbook.xls')
檢查表單名字:
代碼如下:
wb.sheet_names()
得到第一張表單,兩種方式:索引和名字
代碼如下:
sh = wb.sheet_by_index(0)
sh = wb.sheet_by_name(u'Sheet1')
遞歸打印出每行的信息:
代碼如下:
for rownum in range(sh.nrows):
print sh.row_values(rownum)
如果只想返回第一列數據:
代碼如下:
first_column = sh.col_values(0)
[code]
通過索引讀取數據:
[code]
cell_A1 = sh.cell(0,0).value
cell_C4 = sh.cell(rowx=3,colx=2).value
注意:這里的索引都是從0開始的。
二、寫excel
這里介紹一個不錯的包xlwt,可以工作在任何平臺。這也就意味著你可以在Linux下保存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)
|
新聞熱點
疑難解答