成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

python 三種方法實(shí)現(xiàn)對(duì)Excel表格的讀寫(xiě)

瀏覽:11日期:2022-07-04 18:51:15

1、使用xlrd模塊讀取數(shù)據(jù)

# 將excel表格內(nèi)容導(dǎo)入到tables列表中def import_excel(tab): # 創(chuàng)建一個(gè)空列表,存儲(chǔ)Excel的數(shù)據(jù) tables = [] for rown in range(1, tab.nrows): array = {’設(shè)備名稱(chēng)’: ’’, ’框’: ’’, ’槽’: ’’, ’端口’: ’’, ’onuid’: ’’, ’認(rèn)證密碼’: ’’, ’load’: ’’, ’checkcode’: ’’} array[’設(shè)備名稱(chēng)’] = 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[’認(rèn)證密碼’] = tab.cell_value(rown, 9) array[’load’] = tab.cell_value(rown, 10) array[’checkcode’] = tab.cell_value(rown, 11) tables.append(array) return tables# 導(dǎo)入需要讀取Excel表格的路徑data = xlrd.open_workbook(r’G:test.xlsx’)table = data.sheets()[0]for i in import_excel(table): print(i)

2、使用xlwt和openpyxl進(jìn)行寫(xiě)出

import pandas as pd# 要事先下載好xlwt和openpyxl模塊def export_excel(tab): # 將字典列表轉(zhuǎn)換為DataFrame pf = pd.DataFrame(list(tab)) # 指定字段順序 order = [’設(shè)備名稱(chēng)’, ’框’, ’槽’, ’端口’, ’onuid’, ’認(rèn)證密碼’, ’load’, ’checkcode’] pf = pf[order] # 將列名替換為中文 columns_map = { ’設(shè)備名稱(chēng)’: ’設(shè)備名稱(chēng)’, ’框’: ’框’, ’槽’: ’槽’, ’端口’: ’端口’, ’onuid’: ’onuid’, ’認(rèn)證密碼’: ’認(rèn)證密碼’, ’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寫(xiě)出

def export_excel(data, fileName): # xlsxwriter庫(kù)儲(chǔ)存數(shù)據(jù)到excel workbook = xw.Workbook(fileName) # 創(chuàng)建工作簿 worksheet1 = workbook.add_worksheet('sheet1') # 創(chuàng)建子表 worksheet1.activate() # 激活表 title = [’設(shè)備名稱(chēng)’, ’框’, ’槽’, ’端口’, ’onuid’, ’認(rèn)證密碼’, ’load’, ’checkcode’] # 設(shè)置表頭 worksheet1.write_row(’A1’, title) # 從A1單元格開(kāi)始寫(xiě)入表頭 i = 2 # 從第二行開(kāi)始寫(xiě)入數(shù)據(jù) for j in range(len(data)): insertData = [data[j]['設(shè)備名稱(chēng)'], data[j]['框'], data[j]['槽'], data[j]['端口'], data[j]['onuid'], data[j]['認(rèn)證密碼'], data[j]['load'], data[j]['checkcode']] row = ’A’ + str(i) worksheet1.write_row(row, insertData) i += 1 workbook.close() # 關(guān)閉表 export_excel(import_excel(table), 'G:test1.xlsx')

網(wǎng)上有人說(shuō)第三種寫(xiě)入速度快,本人親測(cè)貌似沒(méi)啥其區(qū)別,根據(jù)個(gè)人愛(ài)好寫(xiě)吧,但是xlsxwriter模塊只能寫(xiě)入,無(wú)法修改貌似

以上就是python 三種方法實(shí)現(xiàn)對(duì)Excle表格的讀寫(xiě)的詳細(xì)內(nèi)容,更多關(guān)于python excle表格的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: python
相關(guān)文章: