太棒了!Python和Excel過了這麼久終於可以互通了

太棒了!Python和Excel過了這麼久終於可以互通了

前文

今天為大家分享一篇使用python將大量資料匯出到Excel中的技巧心得,可以讓Python和Excel的資料實現互通!具有很好的參考價值,希望對大家有所幫助(建議在電腦端閱讀,程式碼案例較多)。一起過來看看吧!

問題描述

為了更好地展示資料,Excel格式的資料檔案往往比文字檔案更具有優勢,但是具體到python中,該如何匯出資料到Excel呢?如果碰到需要匯出大量資料又該如何操作呢?

具體步驟

Step 1 安裝openpyxl

使用

pip install openpyxl

即可,但是在windows下安裝的是2。2。6版本,在centos自動安裝的是4。1版本,寫的程式碼在windows下執行沒問題,但centos上卻報錯了,說是ew=ExcelWriter(workbook=wb)少提供一個引數,於是果斷在 237伺服器上我已安裝2。2。6版本的,問題解決。

pip install openpyxl==2。2。6

Step 2 直接上程式碼(Ps:程式碼中包含xlwt和openpyxl的兩個實現版本)

# coding:utf-8‘’‘# 希望對大家有幫助哈,請多提問題create by yaoyzdate: 2017/01/24’‘’importxlrdimportxlwt# workbook相關fromopenpyxl。workbookimportWorkbook# ExcelWriter,封裝了很強大的excel寫的功能fromopenpyxl。writer。excelimportExcelWriter# 一個eggache的數字轉為列字母的方法fromopenpyxl。utilsimportget_column_letterfromopenpyxl。reader。excelimportload_workbookclassHandleExcel():‘’‘Excel相關操作類’‘’def__init__(self):self。 head_row_labels = [u‘學生ID’,u‘學生姓名’,u‘聯絡方式’,u‘知識點ID’,u‘知識點名稱’]“”“ function: 讀出txt檔案中的每一條記錄,把它儲存在list中 Param: filename: 要讀出的檔名 Return: res_list:返回的記錄的list ”“”defread_from_file(self,filename): res_list=[]file_obj=open(filename,“r”)forlineinfile_obj。readlines(): res_list。append(line) file_obj。close()returnres_list“”“ function: 讀出*。xlsx中的每一條記錄,把它儲存在data_dic中返回 Param: excel_name: 要讀出的檔名 Return: data_dic:返回的記錄的dict ”“”defread_excel_with_openpyxl(self, excel_name=“testexcel2007。xlsx”):# 讀取excel2007檔案 wb = load_workbook(filename=excel_name)# 顯示有多少張表print“Worksheet range(s):”, wb。get_named_ranges()print“Worksheet name(s):”, wb。get_sheet_names()# 取第一張表 sheetnames = wb。get_sheet_names()ws = wb。get_sheet_by_name(sheetnames[0])# 顯示錶名,錶行數,表列數print“Work Sheet Titile:”,ws。titleprint“Work Sheet Rows:”,ws。get_highest_row()print“Work Sheet Cols:”,ws。get_highest_column()# 獲取讀入的excel表格的有多少行,有多少列 row_num=ws。get_highest_row() col_num=ws。get_highest_column()print“row_num: ”,row_num,“ col_num: ”,col_num# 建立儲存資料的字典 data_dic = {}sign=1# 把資料存到字典中forrowinws。rows: temp_list=[]# print “row”,rowforcellinrow:printcell。value, temp_list。append(cell。value)print“” data_dic[sign]=temp_listsign+=1printdata_dicreturndata_dic“”“ function: 讀出*。xlsx中的每一條記錄,把它儲存在data_dic中返回 Param: records: 要儲存的,一個包含每一條記錄的list save_excel_name: 儲存為的檔名 head_row_stu_arrive_star: Return: data_dic:返回的記錄的dict ”“”defwrite_to_excel_with_openpyxl(self,records,head_row,save_excel_name=“save。xlsx”):# 新建一個workbook wb = Workbook()# 新建一個excelWriter ew = ExcelWriter(workbook=wb)# 設定檔案輸出路徑與名稱dest_filename = save_excel_name。decode(‘utf-8’)# 第一個sheet是wsws = wb。worksheets[0]# 設定ws的名稱ws。title =“range names”# 寫第一行,標題行forh_xinrange(1,len(head_row)+1): h_col=get_column_letter(h_x)#print h_colws。cell(‘%s%s’% (h_col,1))。value =‘%s’% (head_row[h_x-1])# 寫第二行及其以後的那些行i =2forrecordinrecords:record_list=str(record)。strip()。split(“\t”)forxinrange(1,len(record_list)+1): col = get_column_letter(x)ws。cell(‘%s%s’% (col, i))。value =‘%s’% (record_list[x-1]。decode(‘utf-8’))i +=1# 寫檔案 ew。save(filename=dest_filename)“”“ function: 測試輸出Excel內容 讀出Excel檔案 Param: excel_name: 要讀出的Excel檔名 Return: 無 ”“”defread_excel(self,excel_name): workbook=xlrd。open_workbook(excel_name)printworkbook。sheet_names()# 獲取所有sheetprintworkbook。sheet_names()# [u‘sheet1’, u‘sheet2’]sheet2_name = workbook。sheet_names()[1]# 根據sheet索引或者名稱獲取sheet內容sheet2 = workbook。sheet_by_index(1)# sheet索引從0開始sheet2 = workbook。sheet_by_name(‘Sheet1’)# sheet的名稱,行數,列數printsheet2。name,sheet2。nrows,sheet2。ncols# 獲取整行和整列的值(陣列)rows = sheet2。row_values(3)# 獲取第四行內容cols = sheet2。col_values(2)# 獲取第三列內容printrowsprintcols# 獲取單元格內容printsheet2。cell(1,0)。valueprintsheet2。cell_value(1,0)printsheet2。row(1)[0]。value# 獲取單元格內容的資料型別printsheet2。cell(1,0)。ctype# 透過名稱獲取returnworkbook。sheet_by_name(u‘Sheet1’)“”“ function: 設定單元格樣式 Param: name: 字型名字 height: 字型高度 bold: 是否大寫 Return: style: 返回設定好的格式物件 ”“”defset_style(self,name,height,bold=False):style = xlwt。XFStyle()# 初始化樣式font = xlwt。Font()# 為樣式建立字型font。name = name# ‘Times New Roman’ font。bold = boldfont。color_index =4 font。height = height borders= xlwt。Borders()borders。left=6borders。right=6borders。top=6borders。bottom=6 style。font = font style。borders = bordersreturnstyle“”“ function: 按照 設定單元格樣式 把計算結果由txt轉變為Excel儲存 Param: dataset:要儲存的結果資料,list儲存 Return: 將結果儲存為 excel物件中 ”“”defwrite_to_excel(self, dataset,save_excel_name,head_row):f = xlwt。Workbook()# 建立工作簿# 建立第一個sheet:# sheet1count=1sheet1 = f。add_sheet(u‘sheet1’, cell_overwrite_ok=True)# 建立sheet# 首行標題:forpinrange(len(head_row)):sheet1。write(0,p,head_row[p],self。set_style(‘Times New Roman’,250,True))default=self。set_style(‘Times New Roman’,200,False)# define style out the loop will workforlineindataset:row_list=str(line)。strip(“\n”)。split(“\t”)forppinrange(len(str(line)。strip(“\n”)。split(“\t”))):sheet1。write(count,pp,row_list[pp]。decode(‘utf-8’),default)count+=1f。save(save_excel_name)# 儲存檔案defrun_main_save_to_excel_with_openpyxl(self):print“測試讀寫2007及以後的excel檔案xlsx,以方便寫入檔案更多資料”print“1。 把txt檔案讀入到記憶體中,以list物件儲存”dataset_list=self。read_from_file(“test_excel。txt”)‘’‘test use openpyxl to handle EXCEL 2007’‘’print“2。 把檔案寫入到Excel表格中” head_row_label=self。head_row_labelssave_name=“test_openpyxl。xlsx” self。write_to_excel_with_openpyxl(dataset_list,head_row_label,save_name)print“3。 執行完畢,由txt格式檔案儲存為Excel檔案的任務”defrun_main_save_to_excel_with_xlwt(self):print“ 4。 把txt檔案讀入到記憶體中,以list物件儲存”dataset_list=self。read_from_file(“test_excel。txt”)‘’‘test use xlwt to handle EXCEL 97-2003’‘’print“ 5。 把檔案寫入到Excel表格中” head_row_label=self。head_row_labelssave_name=“test_xlwt。xls” self。write_to_excel_with_openpyxl(dataset_list,head_row_label,save_name)print“6。 執行完畢,由txt格式檔案儲存為Excel檔案的任務”if__name__ ==‘__main__’:print“create handle Excel Object” obj_handle_excel=HandleExcel()# 分別使用openpyxl和xlwt將資料寫入檔案 obj_handle_excel。run_main_save_to_excel_with_openpyxl() obj_handle_excel。run_main_save_to_excel_with_xlwt()‘’‘測試讀出檔案,注意openpyxl不可以讀取xls的檔案,xlrd不可以讀取xlsx格式的檔案’‘’#obj_handle_excel。read_excel_with_openpyxl(“testexcel2003。xls”) # 錯誤寫法#obj_handle_excel。read_excel_with_openpyxl(“testexcel2003。xls”) # 錯誤寫法obj_handle_excel。read_excel(“testexcel2003。xls”)obj_handle_excel。read_excel_with_openpyxl(“testexcel2007。xlsx”)

擴充套件閱讀

透過查閱資料,發現網上眾說紛紜,總結起來有如下幾點:

python Excel相關操作的module lib有兩組,一組是

xlrd、xlwt、xlutils

,另一組是

openpyxl

,但是前一組(xlrd,xlwt)比較老,只能處理由Excel 97-2003 或者Excel 97 以前版本生成的xls格式的excel檔案,xlwt甚至不支援07版以後的excel,這個格式excel檔案一般來說,最大隻能支援256列或者65536行的excel檔案。

因此面對需要匯出大量資料到excel的情況,你將有如下三種選擇:

換一種儲存格式,如儲存為CSV檔案

使用openpyxl—,因為它支援對Excel 2007+ xlsx/xlsm format的處理

win32 COM (Windows only)

當然,我們要直面困難,為了更好地展示資料給產品和使用者,我們依然選擇第二種。

經過一番搜尋後我找到了openpyxl的網址,放在下面了,支援07+的excel,一直有人在維護,文件清晰易讀,參照Tutorial和API文件很快就能上手了,大家有需要的可以自取。

openpyxl網址:https://openpyxl。readthedocs。io/en/stable/

結尾

需要下面這些資料,還有更多課件的請私信我:資料!!!

太棒了!Python和Excel過了這麼久終於可以互通了

太棒了!Python和Excel過了這麼久終於可以互通了