溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么在python中將大量數(shù)據(jù)導(dǎo)出到Excel文件

發(fā)布時(shí)間:2021-01-16 11:09:40 來源:億速云 閱讀:518 作者:Leah 欄目:開發(fā)技術(shù)

這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)怎么在python中將大量數(shù)據(jù)導(dǎo)出到Excel文件,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

1.第一步,安裝openpyxl,

使用pip install openpyxl即可,但是在windows下安裝的是2.2.6版本,但是centos自動(dòng)安裝的是4.1版本,(多謝海哥的提醒)。

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

pip install openpyxl==2.2.6

2.第二步,哈哈,沒有啦,廢話不說了,直接上代碼,ps,代碼中包含xlwt和openpyxl的兩個(gè)實(shí)現(xiàn)版本。

(3)擴(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文件。

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

(1) 換一種存儲(chǔ)格式,如保存為CSV文件

(2) 使用openpyxl—,因?yàn)樗С謱?duì)Excel 2007+ xlsx/xlsm format的處理

(3) win32 COM (Windows only)

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

ps,非常lucky,一番搜索后我找到了openpyxl,支持07+的excel,一直有人在維護(hù),文檔清晰易讀,參照Tutorial和API文檔很快就能上手,就是它了~

(4) 閑話少說,直接上代碼,敬請(qǐng)參考

# coding:utf-8
'''
# 希望對(duì)大家有幫助哈,請(qǐng)多提問題
create by yaoyz
date: 2017/01/24
'''
import xlrd
import xlwt
# workbook相關(guān)
from openpyxl.workbook import Workbook
# ExcelWriter,封裝了很強(qiáng)大的excel寫的功能
from openpyxl.writer.excel import ExcelWriter
# 一個(gè)eggache的數(shù)字轉(zhuǎn)為列字母的方法
from openpyxl.utils import get_column_letter
from openpyxl.reader.excel import load_workbook
class HandleExcel():
 '''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
 """
 def read_from_file(self,filename):
  res_list=[]
  file_obj=open(filename,"r")
  for line in file_obj.readlines():
   res_list.append(line)
  file_obj.close()
  return res_list
 """
  function:
   讀出*.xlsx中的每一條記錄,把它保存在data_dic中返回
  Param:
   excel_name: 要讀出的文件名
  Return:
   data_dic: 返回的記錄的dict
 """
 def read_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])
  # 顯示表名,表行數(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ù)存到字典中
  for row in ws.rows:
   temp_list=[]
   # print "row",row
   for cell in row:
     print cell.value,
     temp_list.append(cell.value)
   print ""
   data_dic[sign]=temp_list
   sign+=1
  print data_dic
  return data_dic
 """
  function:
   讀出*.xlsx中的每一條記錄,把它保存在data_dic中返回
  Param:
   records: 要保存的,一個(gè)包含每一條記錄的list
   save_excel_name: 保存為的文件名
   head_row_stu_arrive_star:
  Return:
   data_dic: 返回的記錄的dict
 """
 def write_to_excel_with_openpyxl(self,records,head_row,save_excel_name="save.xlsx"):
  # 新建一個(gè)workbook
  wb = Workbook()
  # 新建一個(gè)excelWriter
  ew = ExcelWriter(workbook=wb)
  # 設(shè)置文件輸出路徑與名稱
  dest_filename = save_excel_name.decode('utf-8')
  # 第一個(gè)sheet是ws
  ws = wb.worksheets[0]
  # 設(shè)置ws的名稱
  ws.title = "range names"
  # 寫第一行,標(biāo)題行
  for h_x in range(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])
  # 寫第二行及其以后的那些行
  i = 2
  for record in records:
   record_list=str(record).strip().split("\t")
   for x in range(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:
   無
 """
 def read_excel(self,excel_name):
  workbook=xlrd.open_workbook(excel_name)
  print workbook.sheet_names()
  # 獲取所有sheet
  print workbook.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ù)
  print sheet2.name,sheet2.nrows,sheet2.ncols
  # 獲取整行和整列的值(數(shù)組)
  rows = sheet2.row_values(3) # 獲取第四行內(nèi)容
  cols = sheet2.col_values(2) # 獲取第三列內(nèi)容
  print rows
  print cols
  # 獲取單元格內(nèi)容
  print sheet2.cell(1,0).value
  print sheet2.cell_value(1,0)
  print sheet2.row(1)[0].value
  # 獲取單元格內(nèi)容的數(shù)據(jù)類型
  print sheet2.cell(1,0).ctype
  # 通過名稱獲取
  return workbook.sheet_by_name(u'Sheet1')
 """
  function:
   設(shè)置單元格樣式
  Param:
   name: 字體名字
   height: 字體高度
   bold: 是否大寫
  Return:
   style: 返回設(shè)置好的格式對(duì)象
 """
 def set_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
  return style
 """
  function:
   按照 設(shè)置單元格樣式 把計(jì)算結(jié)果由txt轉(zhuǎn)變?yōu)镋xcel存儲(chǔ)
  Param:
   dataset:要保存的結(jié)果數(shù)據(jù),list存儲(chǔ)
  Return:
   將結(jié)果保存為 excel對(duì)象中
 """
 def write_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)題:
  for p in range(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
  for line in dataset:
   row_list=str(line).strip("\n").split("\t")
   for pp in range(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) # 保存文件
 def run_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_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ù)"
 def run_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_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ù)寫入文件
 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ò)誤寫法
 #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")

上述就是小編為大家分享的怎么在python中將大量數(shù)據(jù)導(dǎo)出到Excel文件了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI