日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
太棒了!Python和Excel過了這么久終于可以互通了

 前文

今天為大家分享一篇使用python將大量數(shù)據(jù)導(dǎo)出到Excel中的技巧心得,可以讓Python和Excel的數(shù)據(jù)實(shí)現(xiàn)互通!具有很好的參考價(jià)值,希望對大家有所幫助(建議在電腦端閱讀,代碼案例較多)。一起過來看看吧!

網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)!專注于網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、微信小程序、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了興縣免費(fèi)建站歡迎大家使用!

問題描述

為了更好地展示數(shù)據(jù),Excel格式的數(shù)據(jù)文件往往比文本文件更具有優(yōu)勢,但是具體到python中,該如何導(dǎo)出數(shù)據(jù)到Excel呢?如果碰到需要導(dǎo)出大量數(shù)據(jù)又該如何操作呢?

具體步驟

Step 1 安裝openpyxl

使用 pip install openpyxl 即可,但是在windows下安裝的是2.2.6版本,在centos自動安裝的是4.1版本,寫的代碼在windows下運(yùn)行沒問題,但centos上卻報(bào)錯(cuò)了,說是ew=ExcelWriter(workbook=wb)少提供一個(gè)參數(shù),于是果斷在 237服務(wù)器上我已安裝2.2.6版本的,問題解決。

 
 
 
  1. pip install openpyxl==2.2.6

Step 2 直接上代碼(Ps:代碼中包含xlwt和openpyxl的兩個(gè)實(shí)現(xiàn)版本)

 
 
 
  1. # coding:utf-8
  2. '''
  3. # 希望對大家有幫助哈,請多提問題
  4. create by yaoyz
  5. date: 2017/01/24
  6. '''
  7. importxlrd
  8. importxlwt
  9. # workbook相關(guān)
  10. fromopenpyxl.workbookimportWorkbook
  11. # ExcelWriter,封裝了很強(qiáng)大的excel寫的功能
  12. fromopenpyxl.writer.excelimportExcelWriter
  13. # 一個(gè)eggache的數(shù)字轉(zhuǎn)為列字母的方法
  14. fromopenpyxl.utilsimportget_column_letter
  15. fromopenpyxl.reader.excelimportload_workbook
  16. classHandleExcel():
  17. '''Excel相關(guān)操作類'''
  18. def__init__(self):
  19. self. head_row_labels = [u'學(xué)生ID',u'學(xué)生姓名',u'聯(lián)系方式',u'知識點(diǎn)ID',u'知識點(diǎn)名稱']
  20. """
  21.         function:
  22.             讀出txt文件中的每一條記錄,把它保存在list中
  23.         Param:
  24.             filename:  要讀出的文件名
  25.         Return:
  26.             res_list:返回的記錄的list
  27.     """
  28. defread_from_file(self,filename):
  29.         res_list=[]
  30. file_obj=open(filename,"r")
  31. forlineinfile_obj.readlines():
  32.             res_list.append(line)
  33.         file_obj.close()
  34. returnres_list
  35. """
  36.         function:
  37.             讀出*.xlsx中的每一條記錄,把它保存在data_dic中返回
  38.         Param:
  39.             excel_name:  要讀出的文件名
  40.         Return:
  41.             data_dic:返回的記錄的dict
  42.     """
  43. defread_excel_with_openpyxl(self, excel_name="testexcel2007.xlsx"):
  44. # 讀取excel2007文件
  45.         wb = load_workbook(filename=excel_name)
  46. # 顯示有多少張表
  47. print"Worksheet range(s):", wb.get_named_ranges()
  48. print"Worksheet name(s):", wb.get_sheet_names()
  49. # 取第一張表
  50.         sheetnames = wb.get_sheet_names()
  51. ws = wb.get_sheet_by_name(sheetnames[0])
  52. # 顯示表名,表行數(shù),表列數(shù)
  53. print"Work Sheet Titile:",ws.title
  54. print"Work Sheet Rows:",ws.get_highest_row()
  55. print"Work Sheet Cols:",ws.get_highest_column()
  56. # 獲取讀入的excel表格的有多少行,有多少列
  57.         row_num=ws.get_highest_row()
  58.         col_num=ws.get_highest_column()
  59. print"row_num: ",row_num," col_num: ",col_num
  60. # 建立存儲數(shù)據(jù)的字典
  61.         data_dic = {}
  62. sign=1
  63. # 把數(shù)據(jù)存到字典中
  64. forrowinws.rows:
  65.             temp_list=[]
  66. # print "row",row
  67. forcellinrow:
  68. printcell.value,
  69.                 temp_list.append(cell.value)
  70. print""
  71.             data_dic[sign]=temp_list
  72. sign+=1
  73. printdata_dic
  74. returndata_dic
  75. """
  76.         function:
  77.             讀出*.xlsx中的每一條記錄,把它保存在data_dic中返回
  78.         Param:
  79.             records: 要保存的,一個(gè)包含每一條記錄的list
  80.             save_excel_name:  保存為的文件名
  81.             head_row_stu_arrive_star:
  82.         Return:
  83.             data_dic:返回的記錄的dict
  84.     """
  85. defwrite_to_excel_with_openpyxl(self,records,head_row,save_excel_name="save.xlsx"):
  86. # 新建一個(gè)workbook
  87.         wb = Workbook()
  88. # 新建一個(gè)excelWriter
  89.         ew = ExcelWriter(workbook=wb)
  90. # 設(shè)置文件輸出路徑與名稱
  91. dest_filename = save_excel_name.decode('utf-8')
  92. # 第一個(gè)sheet是ws
  93. ws = wb.worksheets[0]
  94. # 設(shè)置ws的名稱
  95. ws.title ="range names"
  96. # 寫第一行,標(biāo)題行
  97. forh_xinrange(1,len(head_row)+1):
  98.             h_col=get_column_letter(h_x)
  99. #print h_col
  100. ws.cell('%s%s'% (h_col,1)).value ='%s'% (head_row[h_x-1])
  101. # 寫第二行及其以后的那些行
  102. i =2
  103. forrecordinrecords:
  104. record_list=str(record).strip().split("\t")
  105. forxinrange(1,len(record_list)+1):
  106.                 col = get_column_letter(x)
  107. ws.cell('%s%s'% (col, i)).value ='%s'% (record_list[x-1].decode('utf-8'))
  108. i +=1
  109. # 寫文件
  110.         ew.save(filename=dest_filename)
  111. """
  112.         function:
  113.             測試輸出Excel內(nèi)容
  114.             讀出Excel文件
  115.         Param:
  116.             excel_name:  要讀出的Excel文件名
  117.         Return:
  118.           無
  119.     """
  120. defread_excel(self,excel_name):
  121.         workbook=xlrd.open_workbook(excel_name)
  122. printworkbook.sheet_names()
  123. # 獲取所有sheet
  124. printworkbook.sheet_names()# [u'sheet1', u'sheet2']
  125. sheet2_name = workbook.sheet_names()[1]
  126. # 根據(jù)sheet索引或者名稱獲取sheet內(nèi)容
  127. sheet2 = workbook.sheet_by_index(1)# sheet索引從0開始
  128. sheet2 = workbook.sheet_by_name('Sheet1')
  129. # sheet的名稱,行數(shù),列數(shù)
  130. printsheet2.name,sheet2.nrows,sheet2.ncols
  131. # 獲取整行和整列的值(數(shù)組)
  132. rows = sheet2.row_values(3)# 獲取第四行內(nèi)容
  133. cols = sheet2.col_values(2)# 獲取第三列內(nèi)容
  134. printrows
  135. printcols
  136. # 獲取單元格內(nèi)容
  137. printsheet2.cell(1,0).value
  138. printsheet2.cell_value(1,0)
  139. printsheet2.row(1)[0].value
  140. # 獲取單元格內(nèi)容的數(shù)據(jù)類型
  141. printsheet2.cell(1,0).ctype
  142. # 通過名稱獲取
  143. returnworkbook.sheet_by_name(u'Sheet1')
  144. """
  145.         function:
  146.             設(shè)置單元格樣式
  147.         Param:
  148.             name:  字體名字
  149.             height:  字體高度
  150.             bold:  是否大寫
  151.         Return:
  152.             style: 返回設(shè)置好的格式對象
  153.     """
  154. defset_style(self,name,height,bold=False):
  155. style = xlwt.XFStyle()# 初始化樣式
  156. font = xlwt.Font()# 為樣式創(chuàng)建字體
  157. font.name = name# 'Times New Roman'
  158.         font.bold = bold
  159. font.color_index =4
  160.         font.height = height
  161.         borders= xlwt.Borders()
  162. borders.left=6
  163. borders.right=6
  164. borders.top=6
  165. borders.bottom=6
  166.         style.font = font
  167.         style.borders = borders
  168. returnstyle
  169. """
  170.         function:
  171.             按照 設(shè)置單元格樣式  把計(jì)算結(jié)果由txt轉(zhuǎn)變?yōu)镋xcel存儲
  172.         Param:
  173.             dataset:要保存的結(jié)果數(shù)據(jù),list存儲
  174.         Return:
  175.             將結(jié)果保存為 excel對象中
  176.     """
  177. defwrite_to_excel(self, dataset,save_excel_name,head_row):
  178. f = xlwt.Workbook()# 創(chuàng)建工作簿
  179. # 創(chuàng)建第一個(gè)sheet:
  180. # sheet1
  181. count=1
  182. sheet1 = f.add_sheet(u'sheet1', cell_overwrite_ok=True)# 創(chuàng)建sheet
  183. # 首行標(biāo)題:
  184. forpinrange(len(head_row)):
  185. sheet1.write(0,p,head_row[p],self.set_style('Times New Roman',250,True))
  186. default=self.set_style('Times New Roman',200,False)# define style out the loop will work
  187. forlineindataset:
  188. row_list=str(line).strip("\n").split("\t")
  189. forppinrange(len(str(line).strip("\n").split("\t"))):
  190. sheet1.write(count,pp,row_list[pp].decode('utf-8'),default)
  191. count+=1
  192. f.save(save_excel_name)# 保存文件
  193. defrun_main_save_to_excel_with_openpyxl(self):
  194. print"測試讀寫2007及以后的excel文件xlsx,以方便寫入文件更多數(shù)據(jù)"
  195. print"1. 把txt文件讀入到內(nèi)存中,以list對象存儲"
  196. dataset_list=self.read_from_file("test_excel.txt")
  197. '''test use openpyxl to handle EXCEL 2007'''
  198. print"2. 把文件寫入到Excel表格中"
  199.         head_row_label=self.head_row_labels
  200. save_name="test_openpyxl.xlsx"
  201.         self.write_to_excel_with_openpyxl(dataset_list,head_row_label,save_name)
  202. print"3.  執(zhí)行完畢,由txt格式文件保存為Excel文件的任務(wù)"
  203. defrun_main_save_to_excel_with_xlwt(self):
  204. print" 4. 把txt文件讀入到內(nèi)存中,以list對象存儲"
  205. dataset_list=self.read_from_file("test_excel.txt")
  206. '''test use xlwt to handle EXCEL 97-2003'''
  207. print" 5. 把文件寫入到Excel表格中"
  208.         head_row_label=self.head_row_labels
  209. save_name="test_xlwt.xls"
  210.         self.write_to_excel_with_openpyxl(dataset_list,head_row_label,save_name)
  211. print"6.  執(zhí)行完畢,由txt格式文件保存為Excel文件的任務(wù)"
  212. if__name__ =='__main__':
  213. print"create handle Excel Object"
  214.     obj_handle_excel=HandleExcel()
  215. # 分別使用openpyxl和xlwt將數(shù)據(jù)寫入文件
  216.     obj_handle_excel.run_main_save_to_excel_with_openpyxl()
  217.     obj_handle_excel.run_main_save_to_excel_with_xlwt()
  218. '''測試讀出文件,注意openpyxl不可以讀取xls的文件,xlrd不可以讀取xlsx格式的文件'''
  219. #obj_handle_excel.read_excel_with_openpyxl("testexcel2003.xls")  # 錯(cuò)誤寫法
  220. #obj_handle_excel.read_excel_with_openpyxl("testexcel2003.xls") # 錯(cuò)誤寫法
  221. obj_handle_excel.read_excel("testexcel2003.xls")
  222. obj_handle_excel.read_excel_with_openpyxl("testexcel2007.xlsx")

 擴(kuò)展閱讀

通過查閱資料,發(fā)現(xiàn)網(wǎng)上眾說紛紜,總結(jié)起來有如下幾點(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文件一般來說,最大只能支持256列或者65536行的excel文件。

因此面對需要導(dǎo)出大量數(shù)據(jù)到excel的情況,你將有如下三種選擇:

  • 換一種存儲格式,如保存為CSV文件
  • 使用openpyxl—,因?yàn)樗С謱xcel 2007+ xlsx/xlsm format的處理
  • win32 COM (Windows only)

當(dāng)然,我們要直面困難,為了更好地展示數(shù)據(jù)給產(chǎn)品和用戶,我們依然選擇第二種。

經(jīng)過一番搜索后我找到了openpyxl的網(wǎng)址,放在下面了,支持07+的excel,一直有人在維護(hù),文檔清晰易讀,參照Tutorial和API文檔很快就能上手了,大家有需要的可以自取。

  • openpyxl網(wǎng)址:https://openpyxl.readthedocs.io/en/stable/

分享名稱:太棒了!Python和Excel過了這么久終于可以互通了
本文地址:http://www.5511xx.com/article/dhscgeo.html