python 讀取XLSX文件的模塊方法和一般方法對比

import xlrd,os

datadir='/Users/apple/Downloads/tableau_files'
datafile='World Bank CO2 - Tableau Public Learning Resource_zh-CN.xlsx'

def parse_file(datafile):
    workbook=xlrd.open_workbook(datafile)
    sheet=workbook.sheet_by_index(0)

    #二維數據,內層每一個維度都是一行數據
    data=[[sheet.cell_value(r,col)
                for col in range(sheet.ncols)]
                    for r in range(sheet.nrows)]
    #print(data)
    print('\nList Comprehension')
    print('data[2][2]:')
    print(data[2][2])

    print('\nCells in a nested loop:')
    for row in range(sheet.nrows):
        for col in range(sheet.ncols):
            if row==50:
                print(sheet.cell_value(row,col))

    #other useful methods:
    print('\nROWS,COLUMNS,AND CELLS')
    print('Number of rows in the sheet:')
    print(sheet.nrows)
    print('Type of data in celll (row 3,col 2):')
    #單元類型(ctype):0 empty,1 string,2 number, 3 date,4 boolean, 5 error
    print(sheet.cell_type(3,2))
    print('Value in cell (row 3,col 2):')
    print(sheet.cell_value(3,2))
    print('Get a slice of values in column 3,from rows 1-3')
    print(sheet.col_values(3,start_rowx=1,end_rowx=4))

    print('\nDATES')
    print('Type of data in cell  (row1,col 0):')
    print(sheet.cell_type(1,3))
    exceltime=sheet.cell_value(1,3)
    print('Time in Excel format:')
    print(exceltime)
    print('Convert time to a Python datetime tuple,from the Excel float:')
    print(xlrd.xldate_as_tuple(exceltime,0))
    data={
        'maxtime':(0,0,0,0,0,0),
        'maxvalue':0,
        'mintime':(0,0,0,0,0,0),
        'minvalue':0,
        'avgcoast':0
    }
    return data
if __name__=='__main__':
    datafile=os.path.join(datadir,datafile)
    parse_file(datafile)

/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/apple/PycharmProjects/udacity/read_xlsx01.py

List Comprehension
data[2][2]:
拉丁美洲和加勒比海

Cells in a nested loop:
ABW
阿魯巴
拉丁美洲和加勒比海
2009.0
2522.896
24.876705845


ROWS,COLUMNS,AND CELLS
Number of rows in the sheet:
11128
Type of data in celll (row 3,col 2):
1
Value in cell (row 3,col 2):
拉丁美洲和加勒比海
Get a slice of values in column 3,from rows 1-3
[1960.0, 1961.0, 1962.0]


DATES
Type of data in cell  (row1,col 0):
2
Time in Excel format:
1960.0
Convert time to a Python datetime tuple,from the Excel float:
(1905, 5, 13, 0, 0, 0)


Process finished with exit code 0

發佈了101 篇原創文章 · 獲贊 14 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章