python讀取Excel實例


1.操作步驟:


(1)安裝python官方Excel庫-->xlrd

(2)獲取Excel文件位置並讀取

(3)讀取sheet

(4)讀取指定rows和cols內容

2.示例代碼

# -*- coding: utf-8 -*-

import xlrd

from datetime import date,datetime

def read_excel():

#文件位置

ExcelFile=xlrd.open_workbook(r'C:\Users\Administrator\Desktop\TestData.xlsx')

#獲取目標EXCEL文件sheet名

print ExcelFile.sheet_names()

#------------------------------------

#若有多個sheet,則需要指定讀取目標sheet例如讀取sheet2

#sheet2_name=ExcelFile.sheet_names()[1]

#------------------------------------

#獲取sheet內容【1.根據sheet索引2.根據sheet名稱】

#sheet=ExcelFile.sheet_by_index(1)

sheet=ExcelFile.sheet_by_name('TestCase002')

#打印sheet的名稱,行數,列數

print sheet.name,sheet.nrows,sheet.ncols

#獲取整行或者整列的值

rows=sheet.row_values(2)#第三行內容

cols=sheet.col_values(1)#第二列內容

print cols,rows

#獲取單元格內容

print sheet.cell(1,0).value.encode('utf-8')

print sheet.cell_value(1,0).encode('utf-8')

print sheet.row(1)[0].value.encode('utf-8')

#打印單元格內容格式

print sheet.cell(1,0).ctype

if__name__ =='__main__':

read_excel()

 

 

問題1:假如我們修改其中一個值為年份,讀不出正確數字,而是數字



ctype介紹 :

0empty    1string     2number    3date    4boolean    5error

解決方法:先判斷單元格內容再處理



作者:路由心定
鏈接:http://www.jianshu.com/p/d32213e611ea


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM