太棒了!Python和Excel過(guò)了這么久終于可以互通了
前文
今天為大家分享一篇使用python將大量數(shù)據(jù)導(dǎo)出到Excel中的技巧心得,可以讓Python和Excel的數(shù)據(jù)實(shí)現(xiàn)互通!具有很好的參考價(jià)值,希望對(duì)大家有所幫助(建議在電腦端閱讀,代碼案例較多)。一起過(guò)來(lái)看看吧!
問(wèn)題描述
為了更好地展示數(shù)據(jù),Excel格式的數(shù)據(jù)文件往往比文本文件更具有優(yōu)勢(shì),但是具體到python中,該如何導(dǎo)出數(shù)據(jù)到Excel呢?如果碰到需要導(dǎo)出大量數(shù)據(jù)又該如何操作呢?
具體步驟
Step 1 安裝openpyxl
使用 pip install openpyxl 即可,但是在windows下安裝的是2.2.6版本,在centos自動(dòng)安裝的是4.1版本,寫(xiě)的代碼在windows下運(yùn)行沒(méi)問(wèn)題,但centos上卻報(bào)錯(cuò)了,說(shuō)是ew=ExcelWriter(workbook=wb)少提供一個(gè)參數(shù),于是果斷在 237服務(wù)器上我已安裝2.2.6版本的,問(wèn)題解決。
- pip install openpyxl==2.2.6
Step 2 直接上代碼(Ps:代碼中包含xlwt和openpyxl的兩個(gè)實(shí)現(xiàn)版本)
- # coding:utf-8
- '''
- # 希望對(duì)大家有幫助哈,請(qǐng)多提問(wèn)題
- create by yaoyz
- date: 2017/01/24
- '''
- importxlrd
- importxlwt
- # workbook相關(guān)
- fromopenpyxl.workbookimportWorkbook
- # ExcelWriter,封裝了很強(qiáng)大的excel寫(xiě)的功能
- fromopenpyxl.writer.excelimportExcelWriter
- # 一個(gè)eggache的數(shù)字轉(zhuǎn)為列字母的方法
- fromopenpyxl.utilsimportget_column_letter
- fromopenpyxl.reader.excelimportload_workbook
- classHandleExcel():
- '''Excel相關(guān)操作類(lèi)'''
- def__init__(self):
- self. head_row_labels = [u'學(xué)生ID',u'學(xué)生姓名',u'聯(lián)系方式',u'知識(shí)點(diǎn)ID',u'知識(shí)點(diǎn)名稱(chēng)']
- """
- 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)
- # 顯示有多少?gòu)埍?nbsp;
- 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])
- # 顯示表名,表行數(shù),表列數(shù)
- print"Work Sheet Titile:",ws.title
- print"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
- # 建立存儲(chǔ)數(shù)據(jù)的字典
- data_dic = {}
- sign=1
- # 把數(shù)據(jù)存到字典中
- forrowinws.rows:
- temp_list=[]
- # print "row",row
- forcellinrow:
- printcell.value,
- temp_list.append(cell.value)
- print""
- data_dic[sign]=temp_list
- sign+=1
- printdata_dic
- returndata_dic
- """
- function:
- 讀出*.xlsx中的每一條記錄,把它保存在data_dic中返回
- Param:
- records: 要保存的,一個(gè)包含每一條記錄的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"):
- # 新建一個(gè)workbook
- wb = Workbook()
- # 新建一個(gè)excelWriter
- ew = ExcelWriter(workbook=wb)
- # 設(shè)置文件輸出路徑與名稱(chēng)
- dest_filename = save_excel_name.decode('utf-8')
- # 第一個(gè)sheet是ws
- ws = wb.worksheets[0]
- # 設(shè)置ws的名稱(chēng)
- ws.title ="range names"
- # 寫(xiě)第一行,標(biāo)題行
- forh_xinrange(1,len(head_row)+1):
- h_col=get_column_letter(h_x)
- #print h_col
- ws.cell('%s%s'% (h_col,1)).value ='%s'% (head_row[h_x-1])
- # 寫(xiě)第二行及其以后的那些行
- i =2
- forrecordinrecords:
- 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
- # 寫(xiě)文件
- ew.save(filename=dest_filename)
- """
- function:
- 測(cè)試輸出Excel內(nèi)容
- 讀出Excel文件
- Param:
- excel_name: 要讀出的Excel文件名
- Return:
- 無(wú)
- """
- defread_excel(self,excel_name):
- workbook=xlrd.open_workbook(excel_name)
- printworkbook.sheet_names()
- # 獲取所有sheet
- printworkbook.sheet_names()# [u'sheet1', u'sheet2']
- sheet2_name = workbook.sheet_names()[1]
- # 根據(jù)sheet索引或者名稱(chēng)獲取sheet內(nèi)容
- sheet2 = workbook.sheet_by_index(1)# sheet索引從0開(kāi)始
- sheet2 = workbook.sheet_by_name('Sheet1')
- # sheet的名稱(chēng),行數(shù),列數(shù)
- printsheet2.name,sheet2.nrows,sheet2.ncols
- # 獲取整行和整列的值(數(shù)組)
- rows = sheet2.row_values(3)# 獲取第四行內(nèi)容
- cols = sheet2.col_values(2)# 獲取第三列內(nèi)容
- printrows
- printcols
- # 獲取單元格內(nèi)容
- printsheet2.cell(1,0).value
- printsheet2.cell_value(1,0)
- printsheet2.row(1)[0].value
- # 獲取單元格內(nèi)容的數(shù)據(jù)類(lèi)型
- printsheet2.cell(1,0).ctype
- # 通過(guò)名稱(chēng)獲取
- returnworkbook.sheet_by_name(u'Sheet1')
- """
- function:
- 設(shè)置單元格樣式
- Param:
- name: 字體名字
- height: 字體高度
- bold: 是否大寫(xiě)
- Return:
- style: 返回設(shè)置好的格式對(duì)象
- """
- defset_style(self,name,height,bold=False):
- style = xlwt.XFStyle()# 初始化樣式
- font = xlwt.Font()# 為樣式創(chuàng)建字體
- font.name = name# 'Times New Roman'
- font.bold = bold
- font.color_index =4
- font.height = height
- borders= xlwt.Borders()
- borders.left=6
- borders.right=6
- borders.top=6
- borders.bottom=6
- style.font = font
- style.borders = borders
- returnstyle
- """
- function:
- 按照 設(shè)置單元格樣式 把計(jì)算結(jié)果由txt轉(zhuǎn)變?yōu)镋xcel存儲(chǔ)
- Param:
- dataset:要保存的結(jié)果數(shù)據(jù),list存儲(chǔ)
- Return:
- 將結(jié)果保存為 excel對(duì)象中
- """
- defwrite_to_excel(self, dataset,save_excel_name,head_row):
- f = xlwt.Workbook()# 創(chuàng)建工作簿
- # 創(chuàng)建第一個(gè)sheet:
- # sheet1
- count=1
- sheet1 = f.add_sheet(u'sheet1', cell_overwrite_ok=True)# 創(chuàng)建sheet
- # 首行標(biāo)題:
- 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 work
- forlineindataset:
- 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+=1
- f.save(save_excel_name)# 保存文件
- defrun_main_save_to_excel_with_openpyxl(self):
- print"測(cè)試讀寫(xiě)2007及以后的excel文件xlsx,以方便寫(xiě)入文件更多數(shù)據(jù)"
- print"1. 把txt文件讀入到內(nèi)存中,以list對(duì)象存儲(chǔ)"
- dataset_list=self.read_from_file("test_excel.txt")
- '''test use openpyxl to handle EXCEL 2007'''
- print"2. 把文件寫(xiě)入到Excel表格中"
- head_row_label=self.head_row_labels
- save_name="test_openpyxl.xlsx"
- self.write_to_excel_with_openpyxl(dataset_list,head_row_label,save_name)
- print"3. 執(zhí)行完畢,由txt格式文件保存為Excel文件的任務(wù)"
- defrun_main_save_to_excel_with_xlwt(self):
- print" 4. 把txt文件讀入到內(nèi)存中,以list對(duì)象存儲(chǔ)"
- dataset_list=self.read_from_file("test_excel.txt")
- '''test use xlwt to handle EXCEL 97-2003'''
- print" 5. 把文件寫(xiě)入到Excel表格中"
- head_row_label=self.head_row_labels
- save_name="test_xlwt.xls"
- self.write_to_excel_with_openpyxl(dataset_list,head_row_label,save_name)
- print"6. 執(zhí)行完畢,由txt格式文件保存為Excel文件的任務(wù)"
- if__name__ =='__main__':
- print"create handle Excel Object"
- obj_handle_excel=HandleExcel()
- # 分別使用openpyxl和xlwt將數(shù)據(jù)寫(xiě)入文件
- obj_handle_excel.run_main_save_to_excel_with_openpyxl()
- obj_handle_excel.run_main_save_to_excel_with_xlwt()
- '''測(cè)試讀出文件,注意openpyxl不可以讀取xls的文件,xlrd不可以讀取xlsx格式的文件'''
- #obj_handle_excel.read_excel_with_openpyxl("testexcel2003.xls") # 錯(cuò)誤寫(xiě)法
- #obj_handle_excel.read_excel_with_openpyxl("testexcel2003.xls") # 錯(cuò)誤寫(xiě)法
- obj_handle_excel.read_excel("testexcel2003.xls")
- obj_handle_excel.read_excel_with_openpyxl("testexcel2007.xlsx")
擴(kuò)展閱讀
通過(guò)查閱資料,發(fā)現(xiàn)網(wǎng)上眾說(shuō)紛紜,總結(jié)起來(lái)有如下幾點(diǎn):
python Excel相關(guān)操作的module lib有兩組,一組是 xlrd、xlwt、xlutils ,另一組是 openpyxl,但是前一組(xlrd,xlwt)比較老,只能處理由Excel 97-2003 或者Excel 97 以前版本生成的xls格式的excel文件,xlwt甚至不支持07版以后的excel,這個(gè)格式excel文件一般來(lái)說(shuō),最大只能支持256列或者65536行的excel文件。
因此面對(duì)需要導(dǎo)出大量數(shù)據(jù)到excel的情況,你將有如下三種選擇:
- 換一種存儲(chǔ)格式,如保存為CSV文件
- 使用openpyxl—,因?yàn)樗С謱?duì)Excel 2007+ xlsx/xlsm format的處理
- win32 COM (Windows only)
當(dāng)然,我們要直面困難,為了更好地展示數(shù)據(jù)給產(chǎn)品和用戶(hù),我們依然選擇第二種。
經(jīng)過(guò)一番搜索后我找到了openpyxl的網(wǎng)址,放在下面了,支持07+的excel,一直有人在維護(hù),文檔清晰易讀,參照Tutorial和API文檔很快就能上手了,大家有需要的可以自取。
- openpyxl網(wǎng)址:https://openpyxl.readthedocs.io/en/stable/