• python_excel


    1. xlrd, xlwt, xlutils的关系

    Python中一般使用xlrd(excel read)来读取Excel文件,使用xlwt(excel write)来生成Excel文件(可以控制Excel中单元格的格式),需要注意的是,用xlrd读 取excel是不能对其进行操作的:xlrd.open_workbook()方法返回xlrd.Book类型,是只读的,不能对其进行操作。而 xlwt.Workbook()返回的xlwt.Workbook类型的save(filepath)方法可以保存excel文件。因此对于读取和生成Excel文件都非常容易处理,但是对于已经存在的Excel文件进行修改就比较麻烦了。不过,还有一个xlutils(依赖于xlrd和xlwt)提供复制excel文件内容和修改文件的功能。

    2. xlrd, xlwt, xlutils的安装过程,以xlrd为例()

    (1)http://pypi.python.org/pypi/xlrd下载xlrd-0.7.7.tar.gz。

    (2)把下载的.gz包解压,如我把它们解压到F:DOWNLOAD下。

    (3)在win7下打开cmd,在命令行输入F:,切换到F盘,再cd DOWNLOADxlrd-0.7.7,再输入 setup.py install.装完了。

    xlwt的下载地址:https://pypi.python.org/pypi/xlwt

    xlutils的下载地址:https://pypi.python.org/pypi/xlutils

    3. xlrd, xlwt, xlutils三个包的API参考地址

    http://pypi.python.org/pypi/xlrd

    http://pypi.python.org/pypi/xlwt

    http://pypi.python.org/pypi/xlutils

    4. 使用xlrd读Excel

    open_workbook()打开指定的Excel文件,返回一个Book对象。

    通过Book对象可以得到各个Sheet对象(一个Excel文件可以有多个Sheet,每个Sheet就是一张表格)。

    Book.nsheets返回Sheet的数目。

    Book.sheets()返回所有Sheet对象的list。

    Book.sheet_by_index(index)返回指定索引处的Sheet。相当于Book.sheets()[index]。

    Book.sheet_names()返回所有Sheet对象名字的list。

    Book.sheet_by_name(name)根据指定Sheet对象名字返回Sheet。

    通过Sheet对象可以获取各个单元格,每个单元格是一个Cell对象。

    Sheet.name返回表格的名称。

    Sheet.nrows返回表格的行数。

    Sheet.ncols返回表格的列数。

    Sheet.row(r)获取指定行,返回Cell对象的list。

    Sheet.row_values(r)获取指定行的值,返回list。

    Sheet.col(c)获取指定列,返回Cell对象的list。

    Sheet.col_values(c)获取指定列的值,返回list。

    Sheet.cell(r, c)根据位置获取Cell对象。

    Sheet.cell_value(r, c)根据位置获取Cell对象的值。

    Cell.value返回单元格的值。

    5. 使用xlwt写Excel

    Workbook()是构造函数,返回一个工作簿的对象。

    Workbook.add_sheet(name)添加了一个名为name的表,类型为Worksheet。

    Workbook.get_sheet(index)可以根据索引返回Worksheet(前提是已经添加到Workbook中了)。

    Worksheet.write(r, c, vlaue)是将vlaue填充到指定位置。

    Worksheet.row(n)返回指定的行。

    Row.write(c, value)在某一行的指定列写入value。

    Worksheet.col(n)返回指定的列。

    6. 使用xlutils的copy函数

    from xlutils.copy import copy

    wb = copy(rb)

    rb是xlrd对应的读workbook,wb则对应xlwt对应的写workbook,wb可进行写的所有操作

    7. 示例

    【设计思想】

    (1) 新增或者打开一个已存在的excel表格,excel表格存在一个工作本(Sheet1)

    (2) 向excel表格中加入列名

    (3) 向excel表格中加入每列的值

    【代码】

    #-*- coding:utf-8 -*-
    import xlrd
    import xlwt
    import os
    from xlutils.copy import copy
    
    #excel表格只存在一张工作表,每次保存之后,需要再重新打开一次excel表格
    class OperateExcel():
    
        def __init__(self, filePath):
            self.filePath = filePath
    
        def open_excel(self):
            """打开excel"""
            if not os.path.exists(self.filePath):
                workbook = xlwt.Workbook("utf-8")
                sheet = workbook.add_sheet(u"Sheet1")
                workbook.save(filePath)
            self.rb = xlrd.open_workbook(filePath)
            self.rs = self.rb.sheet_by_name(u"Sheet1")
            self.wb = copy(self.rb)
            self.ws = self.wb.get_sheet(0)
    
        def set_col_name(self, colNames):
            """先建立excel表格的列"""
            colNum = len(colNames)
            for colNo in range(0, colNum):
                self.ws.write(0, colNo, colNames[colNo])
    
            self.save_excel()
            self.open_excel()
    
        def get_colnumber_by_colname(self, colName):
            """获取某一列的列号"""
            len = self.rs.row_len(0)
            for colNo in range(0, len):
                if self.rs.cell_value(0, colNo) == colName:
                    return  colNo
    
            print "excel表中不存在列名:%s" % colName
            return -1
    
    
        def write_excel(self, rowValue):
            """向excel表格的默认追加内容"""
    
            keys = rowValue.keys()
            for key in keys:
                self.ws.write(self.rs.nrows, self.get_colnumber_by_colname(key), rowValue.get(key))
    
            self.save_excel()
            self.open_excel()
    
        def save_excel(self):
            """关闭excel"""
            self.wb.save(self.filePath)
    
    
    
    if __name__ == "__main__":
        filePath = u"E:/test.xls"
        colName = (u"姓名",u"年龄",u"性别",u"学历")
    
        rowValuesList = list()
        rowValue1 = {u"姓名":u"张三", u"年龄":u"20", u"性别":u"", u"姓名":u"本科" }
        rowValue2 = {u"姓名":u"李四", u"年龄":u"18" }
        rowValue3 = {u"姓名":u"王五", u"性别":u"" }
        rowValuesList.append(rowValue1)
        rowValuesList.append(rowValue2)
        rowValuesList.append(rowValue3)
    
        excel = OperateExcel(filePath)
        excel.open_excel()
        excel.set_col_name(colName)
        for rowValue in rowValuesList:
            excel.write_excel(rowValue)
        excel.save_excel()


    8. 备注

    描述内容,都来源于网络

     

  • 相关阅读:
    在WPF中应用弱事件模式
    MSTest DeploymentItemAttribute
    delegate, event
    zookeeper 开机启动197
    centos 7 安装solr7.3.0 配置mysql197
    solr7.4 centos7安装197
    centos 查看mysql数据库命令197
    bootstrapValidator验证197
    idea快捷键197
    sun.misc.Unsafe.park(Native Method)197
  • 原文地址:https://www.cnblogs.com/zhuhaiying/p/6150012.html
Copyright © 2020-2023  润新知