【python】讀寫excel
阿新 • • 發佈:2018-12-08
轉載:http://blog.csdn.net/majordong100/article/details/50708365
學習Python的過程中,我們會遇到Excel的讀寫問題。通過搜尋得知,我們可以使用xlwt module將資料寫入Excel表格,使用xlrd module從Excel讀取資料。下面介紹如何實現使用Python對Excel進行讀寫操作。
Python版本:2.7.11
通過pip安裝xlwt, xlrd這兩個模組,如果沒有安裝的話:
pip install xlwt
pip insall xlrd
對Excel檔案進行寫入操作:
- # -*- coding: UTF-8 -*-
- # How to write to an Excel using xlwt module
- import xlwt
- # 建立一個Workbook物件,這就相當於建立了一個Excel檔案
- book = xlwt.Workbook(encoding='utf-8', style_compression=0)
- # 建立一個sheet物件,一個sheet物件對應Excel檔案中的一張表格。
- # 在電腦桌面右鍵新建一個Excel檔案,其中就包含sheet1,sheet2,sheet3三張表
- sheet = book.add_sheet('aa', cell_overwrite_ok=
- # 向表aa中新增資料
- sheet.write(0, 0, 'EnglishName') # 其中的'0, 0'指定表中的單元,'EnglishName'是向該單元寫入的內容
- sheet.write(1, 0, 'Marcovaldo')
- txt1 = '中文名字'
- sheet.write(0, 1, txt1.decode('utf-8')) # 此處需要將中文字串解碼成unicode碼,否則會報錯
- txt2 = '馬可瓦多'
- sheet.write(1, 1, txt2.decode('utf-8'))
- # 最後,將以上操作儲存到指定的Excel檔案中
- book.save(r'e:\try1.xls') #在字串前加r,宣告為raw字串,這樣就不會處理其中的轉義了。否則,可能會報錯
對Excel檔案進行讀取操作:
[python] view plain copy
- # -*- coding: UTF-8 -*-
- # How to read from an Excel using xlrd module
- import xlrd
- # 開啟指定路徑中的xls檔案
- xlsfile = r'e:\try1.xls'
- book = xlrd.open_workbook(xlsfile) # 得到Excel檔案的book物件
- # 得到sheet物件
- sheet0 = book.sheet_by_index(0) # 通過sheet索引獲得sheet物件
- sheet_name = book.sheet_names()[0] # 獲得指定索引的sheet名字
- print sheet_name
- sheet1 = book.sheet_by_name(sheet_name) # 通過sheet名字來獲取,當然如果知道sheet名字就可以直接指定
- # 獲得行數和列數
- nrows = sheet0.nrows # 行總數
- ncols = sheet0.ncols # 列總數
- # 獲得指定行、列的值,返回物件為一個值列表
- row_data = sheet0.row_values(0) # 獲得第1行的資料列表
- print row_data
- col_data = sheet0.col_values(0) # 獲得第1列的資料列表
- # 通過座標讀取表格中的資料
- cell_value1 = sheet0.cell_value(0, 0)
- print cell_value1
- cell_value2 = sheet0.cell_value(0, 1)
- print cell_value2