python 三種方法實現對Excel表格的讀寫
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模塊只能寫入,無法修改貌似
以上就是python 三種方法實現對Excle表格的讀寫的詳細內容,更多關于python excle表格的資料請關注好吧啦網其它相關文章!
相關文章:
1. CentOS郵件服務器搭建系列—— POP / IMAP 服務器的構建( Dovecot )2. MyBatis JdbcType 與Oracle、MySql數據類型對應關系說明3. ASP中if語句、select 、while循環的使用方法4. 存儲于xml中需要的HTML轉義代碼5. phpstudy apache開啟ssi使用詳解6. jsp網頁實現貪吃蛇小游戲7. .NET SkiaSharp 生成二維碼驗證碼及指定區域截取方法實現8. django創建css文件夾的具體方法9. Django model重寫save方法及update踩坑詳解10. ASP中實現字符部位類似.NET里String對象的PadLeft和PadRight函數
