天天看點

python3讀取excel檔案(xls/xlsx)

第一種方法:打開Excel檔案,另存為 .csv檔案即可,利用讀取csv的方式

第二種方法:

第一步: pip install pyexcel-xls
           

環境:python3.6

工具:pycharm2017.3 community

上代碼:

# 讀取檔案

# pyexcel_xls 以 OrderedDict 結構處理資料

from collections import OrderedDict

from pyexcel_xls import get_data

from pyexcel_xls import save_data

def read_xls_file():

    xls_data = get_data(r"D:\read_test.xlsx")

    print ("Get data type:", type(xls_data))

    for sheet_n in xls_data.keys():

        print (sheet_n, ":", xls_data[sheet_n])

if __name__ == '__main__':

    read_xls_file()

# 寫入檔案

from collections import OrderedDict

from pyexcel_xls import get_data

from pyexcel_xls import save_data

def read_xls_file():

    xls_data = get_data(unicode(r"D:\試試.xlsx", "utf-8"))

    print( "Get data type:", type(xls_data))

    for sheet_n in xls_data.keys():

        print (sheet_n, ":", xls_data[sheet_n])

    return xls_data

# 寫Excel資料, xls格式

def save_xls_file():

    data = OrderedDict()

    # sheet表的資料

    sheet_1 = []

    row_1_data = [u"ID", u"昵稱", u"等級"]   # 每一行的資料

    row_2_data = [4, 5, 6]

    # 逐條添加資料

    sheet_1.append(row_1_data)

    sheet_1.append(row_2_data)

    # 添加sheet表

    data.update({u"這是XX表": sheet_1})

    # 儲存成xls檔案

    save_data("D:\write_test.xls", data)

if __name__ == '__main__':

    save_xls_file()

------------------

reference:https://blog.csdn.net/chenggong2dm/article/details/44956805