python read Excel instance
1. Operation steps:
(1) Install python official Excel library --> xlrd
(2) Get the Excel file location and read
(3) Read sheet
(4) Read the contents of the specified rows and cols
2. Sample code
# -*- coding: utf-8 -*-
import xlrd
from datetime import date,datetime
def read_excel():
#file location
ExcelFile=xlrd.open_workbook(r'C:\Users\Administrator\Desktop\TestData.xlsx')
#Get the sheet name of the target EXCEL file
print ExcelFile.sheet_names()
#------------------------------------
#If there are multiple sheets, you need to specify the read target sheet, such as reading sheet2
#sheet2_name=ExcelFile.sheet_names()[1]
#------------------------------------
#Get sheet content [1. According to sheet index 2. According to sheet name]
#sheet=ExcelFile.sheet_by_index(1)
sheet=ExcelFile.sheet_by_name('工作表1')
#Print the name of the sheet, the number of rows, and the number of columns
print sheet.name,sheet.nrows,sheet.ncols
#Get the value of the entire row or column
rows=sheet.row_values(2)#The content of the third row
cols=sheet.col_values(1)#The content of the second column
print cols,rows
#Get the cell content
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()
输出:
ctype介绍 :
0empty 1string 2number 3date 4boolean 5error