python与excel互通_【好消息】Python和Excel终于可以互通了!!
'''# 希望對(duì)大家有幫助哈,請(qǐng)多提問題create by yaoyzdate: 2017/01/24'''importxlrdimportxlwt# workbook相關(guān)fromopenpyxl.workbookimportWorkbook# ExcelWriter,封裝了很強(qiáng)大的excel寫的功能fromopenpyxl.writer.excelimportExcelWriter# 一個(gè)eggache的數(shù)字轉(zhuǎn)為列字母的方法fromopenpyxl.utilsimportget_column_letterfromopenpyxl.reader.excelimportload_workbookclassHandleExcel:'''Excel相關(guān)操作類'''def__init__(self):self. head_row_labels = [ u'學(xué)生ID', u'學(xué)生姓名', u'聯(lián)系方式', u'知識(shí)點(diǎn)ID', u'知識(shí)點(diǎn)名稱']"""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.closereturnres_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_rangesprint"Worksheet name(s):", wb.get_sheet_names# 取第一張表sheetnames = wb.get_sheet_namesws = wb.get_sheet_by_name(sheetnames[ 0])# 顯示表名,表行數(shù),表列數(shù)print"Work Sheet Titile:",ws.titleprint"Work Sheet Rows:",ws.get_highest_rowprint"Work Sheet Cols:",ws.get_highest_column# 獲取讀入的excel表格的有多少行,有多少列row_num=ws.get_highest_rowcol_num=ws.get_highest_columnprint"row_num: ",row_num, " col_num: ",col_num# 建立存儲(chǔ)數(shù)據(jù)的字典data_dic = {}sign= 1# 把數(shù)據(jù)存到字典中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: 要保存的,一個(gè)包含每一條記錄的listsave_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è)workbookwb = Workbook# 新建一個(gè)excelWriterew = ExcelWriter(workbook=wb)# 設(shè)置文件輸出路徑與名稱dest_filename = save_excel_name.decode( 'utf-8')# 第一個(gè)sheet是wsws = wb.worksheets[ 0]# 設(shè)置ws的名稱ws.title = "range names"# 寫第一行,標(biāo)題行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:測(cè)試輸出Excel內(nèi)容讀出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]# 根據(jù)sheet索引或者名稱獲取sheet內(nèi)容sheet2 = workbook.sheet_by_index( 1) # sheet索引從0開始sheet2 = workbook.sheet_by_name( 'Sheet1')# sheet的名稱,行數(shù),列數(shù)printsheet2.name,sheet2.nrows,sheet2.ncols# 獲取整行和整列的值(數(shù)組)rows = sheet2.row_values( 3) # 獲取第四行內(nèi)容cols = sheet2.col_values( 2) # 獲取第三列內(nèi)容printrowsprintcols# 獲取單元格內(nèi)容printsheet2.cell( 1, 0).valueprintsheet2.cell_value( 1, 0)printsheet2.row( 1)[ 0].value# 獲取單元格內(nèi)容的數(shù)據(jù)類型printsheet2.cell( 1, 0).ctype# 通過名稱獲取returnworkbook.sheet_by_name( u'Sheet1')"""function:設(shè)置單元格樣式Param:name: 字體名字height: 字體高度bold: 是否大寫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 = boldfont.color_index = 4font.height = heightborders= xlwt.Bordersborders.left= 6borders.right= 6borders.top= 6borders.bottom= 6style.font = fontstyle.borders = bordersreturnstyle"""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:# sheet1count= 1sheet1 = 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 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"測(cè)試讀寫2007及以后的excel文件xlsx,以方便寫入文件更多數(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. 把文件寫入到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. 執(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. 把文件寫入到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. 執(zhí)行完畢,由txt格式文件保存為Excel文件的任務(wù)"if__name__ == '__main__':print"create handle Excel Object"obj_handle_excel=HandleExcel# 分別使用openpyxl和xlwt將數(shù)據(jù)寫入文件obj_handle_excel.run_main_save_to_excel_with_openpyxlobj_handle_excel.run_main_save_to_excel_with_xlwt'''測(cè)試讀出文件,注意openpyxl不可以讀取xls的文件,xlrd不可以讀取xlsx格式的文件'''#obj_handle_excel.read_excel_with_openpyxl("testexcel2003.xls") # 錯(cuò)誤寫法#obj_handle_excel.read_excel_with_openpyxl("testexcel2003.xls") # 錯(cuò)誤寫法obj_handle_excel.read_excel( "testexcel2003.xls")obj_handle_excel.read_excel_with_openpyxl( "testexcel2007.xlsx")
總結(jié)
以上是生活随笔為你收集整理的python与excel互通_【好消息】Python和Excel终于可以互通了!!的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 陋室铭的作者是谁啊?
- 下一篇: python查找字符串出现次数_Pyth