• 如何使用python将大量数据导出到Excel中的小技巧之一


    如何使用python将大量数据导出到Excel中的小技巧

       (1) 问题描述:为了更好地展示数据,Excel格式的数据文件往往比文本文件更具有优势,但是具体到python中,该如何导出数据到Excel呢?如果碰到需要导出大量数据又该如何操作呢?本文主要解决以上两个问题。

     PS注意:很多人学Python过程中会遇到各种烦恼问题,没有人帮答疑容易放弃。为此小编建了个Python全栈免费答疑.裙 :七衣衣九起起巴而五(数字的谐音)转换下可以找到了,不懂的问题有老司机解决里面还有最新Python教程项目可拿,,一起相互监督共同进步!

    (2)具体步骤如下:

    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

    2.第二步,哈哈,没有啦,废话不说了,直接上代码,ps,代码中包含xlwt和openpyxl的两个实现版本。

     (3)扩展阅读:通过查阅资料,发现网上众说纷纭,总结起来有如下几点:

     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的情况,你将有如下三种选择,1)换一种存储格式,如保存为CSV文件  2)使用openpyxl—,因为它支持对Excel 2007+ xlsx/xlsm format的处理  3) win32 COM (Windows only)

    当然,我们要直面困难了,为了更好地展示数据给产品和用户,我们依然选择的第二种。

    ps,非常lucky,一番搜索后我找到了openpyxl,支持07+的excel,一直有人在维护,文档清晰易读,参照Tutorial和API文档很快就能上手,就是它了~

    【20180713 add ps,以下代码在 openpyxl 的__version__ = '2.2.6' 和   openpyxl 的__version__ = '2.4.8' 测试通过 ,考虑到openpyxl的最新版本是__version__ = '2.5.4' , 如需最新版本python操作excel的例子

       (4)闲话少说,直接上代码,敬请参考

    # coding:utf-8

    '''

    # 希望对大家有帮助哈,请多提问题

    create by yaoyz

    date: 2017/01/24

    '''

    importxlrd

    importxlwt

    # workbook相关

    fromopenpyxl.workbookimportWorkbook

    # ExcelWriter,封装了很强大的excel写的功能

    fromopenpyxl.writer.excelimportExcelWriter

    # 一个eggache的数字转为列字母的方法

    fromopenpyxl.utilsimportget_column_letter

    fromopenpyxl.reader.excelimportload_workbook

    classHandleExcel():

    '''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.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

    # 建立存储数据的字典

            data_dic = {}

    sign=1

    # 把数据存到字典中

    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: 要保存的,一个包含每一条记录的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是ws

    ws = wb.worksheets[0]

    # 设置ws的名称

    ws.title ="range names"

    # 写第一行,标题行

    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])

    # 写第二行及其以后的那些行

    i =2

    forrecordinrecords:

    record_list=str(record).strip().split(" ")

    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()

    # 获取所有sheet

    printworkbook.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)# 获取第三列内容

    printrows

    printcols

    # 获取单元格内容

    printsheet2.cell(1,0).value

    printsheet2.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 = 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:

                按照 设置单元格样式  把计算结果由txt转变为Excel存储

            Param:

                dataset:要保存的结果数据,list存储

            Return:

                将结果保存为 excel对象中

        """

    defwrite_to_excel(self, dataset,save_excel_name,head_row):

    f = xlwt.Workbook()# 创建工作簿

    # 创建第一个sheet:

    # sheet1

    count=1

    sheet1 = 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 work

    forlineindataset:

    row_list=str(line).strip(" ").split(" ")

    forppinrange(len(str(line).strip(" ").split(" "))):

    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"测试读写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_labels

    save_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_labels

    save_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过程中会遇到各种烦恼问题,没有人帮答疑容易放弃。为此小编建了个Python全栈免费答疑.裙 :七衣衣九起起巴而五(数字的谐音)转换下可以找到了,不懂的问题有老司机解决里面还有最新Python教程项目可拿,,一起相互监督共同进步!

    本文的文字及图片来源于网络加上自己的想法,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理。

  • 相关阅读:
    Multi-Channel Buffers
    FFmpeg 的bug
    关于游戏的网络同步探索1
    预处理、编译、汇编、链接、启动代码、相关command
    Linux命令——whiptail交互式shell脚本对话框
    实模式、保护模式、三种地址、分段、分页
    XAMPP + PhpStorm + Xdebug本地实验环境搭建
    Web数据库架构
    PHP语法基础
    A quick introduction to Source Insight for seamless development platform between Linux and Windows
  • 原文地址:https://www.cnblogs.com/chengxuyuanaa/p/12434220.html
Copyright © 2020-2023  润新知