由於常常用到對excel的相關操做,今天就在此總結相關內容,方便你們參考。html
python操做excel除了讀就是寫。python
經過open_workbook返回的xlrd.Book對象包含了全部對工做簿要的事情,能被用於在工做簿中取得獨立的sheet。web
這個nsheets屬性是一個整數,包含工做簿sheet的數量。這個屬性與sheet_by_index方法結合起來是獲取獨立sheet最經常使用的方法。數組
從讀開始ide
sheet_names方法返回包含工做簿中全部sheet名字的unicode列表。單獨的sheet能夠經過sheet_by_name方法使用這些名字獲取。字體
sheets方法的結果是迭代獲取工做簿中的每一個sheet。編碼
from xlrd import open_workbook book = open_workbook('simple.xls') print book.nsheets for sheet_index in range(book.nsheets): print book.sheet_by_index(sheet_index) print book.sheet_names() for sheet_name in book.sheet_names(): print book.sheet_by_name(sheet_name) for sheet in book.sheets(): print sheet
xlrd.Book對象有與工做簿內容相關的其它屬性,但不多用到:spa
若是你可能須要運用這些屬性,請查看xlrd文檔。excel
經過上面介紹的方法返回的xlrd.sheet.Sheet對象包含了全部對worksheet和它的內容操做的信息。code
name屬性是worksheet名字的unicode表示。
nrows和ncols屬性分別包含了worksheet中的行數和列數。
下面例子展現瞭如何使用迭代來顯示一個worksheet的內容:
由xlrd產生的全部文本屬性不是unidecode對象,就是ascii字符串(不多)。
由Microsoft Excel輸入的每一個文本都是下列編碼之一:
其餘知名軟件用錯誤字符集或不用字符集寫入Excel文件的狀況是不多的。這種狀況下,可能須要在open_workbook方法中指定正確的字符集。
from xlrd import open_workbook book = open_workbook('dodgy.xls',encoding='cp1252')
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
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, 展現如何建立超連接 (hint: you need to use a formula)
merged.py, 展現如何合併格子
row_styles.py, 展現如何應用Style到整行格子中.
若是你在操做特別大的Excel文件,那麼有兩個你應該注意的xlrd特性:
下面的例子展現了一個大的workbook怎麼去迭代被檢查只匹配某一模式的sheet,並在內存中某個時間被卸載。
from xlrd import open_workbook book = open_workbook('simple.xls',on_demand=True) for name in book.sheet_names(): if name.endswith('2'): sheet = book.sheet_by_name(name) print sheet.cell_value(0,0) book.unload_sheet(name)
參考http://blog.sina.com.cn/s/blog_63f0cfb20100o617.html