1. 程式人生 > 實用技巧 >python實現對Excle表格的讀寫

python實現對Excle表格的讀寫

1、使用xlrd模組讀取資料

# 將excel表格內容匯入到tables列表中
def import_excel(tab):
    # 建立一個空列表,儲存Excel的資料
    tables = []
    for rown in range(1, tab.nrows):
        array = {'裝置名稱': '', '': '', '': '', '': '', 'onuid': '', '認證密碼': '', 'load': '', 'checkcode': ''}
        array['裝置名稱'] = tab.cell_value(rown, 0)
        array[
''] = tab.cell_value(rown, 1) array[''] = tab.cell_value(rown, 2) array[''] = tab.cell_value(rown, 3) array['onuid'] = tab.cell_value(rown, 4) array['認證密碼'] = tab.cell_value(rown, 9) array['load'] = tab.cell_value(rown, 10) array['checkcode'] = tab.cell_value(rown, 11) tables.append(array)
return tables # 匯入需要讀取Excel表格的路徑 data = xlrd.open_workbook(r'G:\\test.xlsx') table = data.sheets()[0] for i in import_excel(table): print(i)

2、使用xlwt和openpyxl進行寫出

import pandas as pd
# 要事先下載好xlwt和openpyxl模組
def export_excel(tab):
    # 將字典列表轉換為DataFrame
    pf = pd.DataFrame(list(tab))
    # 指定欄位順序
order = ['裝置名稱', '', '', '', 'onuid', '認證密碼', 'load', 'checkcode'] pf = pf[order] # 將列名替換為中文 columns_map = { '裝置名稱': '裝置名稱', '': '', '': '', '': '', 'onuid': 'onuid', '認證密碼': '認證密碼', 'load': 'load', 'checkcode': 'checkcode' } pf.rename(columns=columns_map, inplace=True) # 指定生成的Excel表格路徑 file_path = pd.ExcelWriter('G:\\test1.xlsx') # 替換空單元格 pf.fillna(' ', inplace=True) # 輸出 pf.to_excel(file_path, encoding='utf-8', index=False) # 儲存表格 file_path.save()
export_excel(tables)

3、使用xlsxwriter寫出

def export_excel(data, fileName):  # xlsxwriter庫儲存資料到excel
    workbook = xw.Workbook(fileName)  # 建立工作簿
    worksheet1 = workbook.add_worksheet("sheet1")  # 建立子表
    worksheet1.activate()  # 啟用表
    title = ['裝置名稱', '', '', '', 'onuid', '認證密碼', 'load', 'checkcode']  # 設定表頭
    worksheet1.write_row('A1', title)  # 從A1單元格開始寫入表頭
    i = 2  # 從第二行開始寫入資料
    for j in range(len(data)):
        insertData = [data[j]["裝置名稱"], data[j][""], data[j][""], data[j][""], data[j]["onuid"], data[j]["認證密碼"],
                      data[j]["load"], data[j]["checkcode"]]
        row = 'A' + str(i)
        worksheet1.write_row(row, insertData)
        i += 1
    workbook.close()  # 關閉表

 export_excel(import_excel(table), "G:\\test1.xlsx")

網上有人說第三種寫入速度快,本人親測貌似沒啥其區別,根據個人愛好寫吧,但是xlsxwriter模組只能寫入,無法修改貌似