zoukankan      html  css  js  c++  java
  • Python处理Excel文档之openpyxl

    openpyxl 可以很好的处理 2010版本以上的表格。

    示例:

     1 #coding:utf8
     2 '''
     3 Created on 2018年8月18日
     4 
     5 @author: Administrator
     6 '''
     7 from openpyxl import Workbook
     8 import datetime
     9 wb = Workbook()
    10 
    11 # grab the active worksheet
    12 ws = wb.active
    13 
    14 # Data can be assigned directly to cells
    15 ws['A1'] = "班级人员统计表"
    16 
    17 # Rows can also be appended
    18 list_str=["记录时间","学号","姓名","性别","年龄"]
    19 ws.append(list_str)
    20 
    21 list_str2=["1","诸葛亮","","89"]
    22 time1=datetime.date.today()
    23 list_str2.insert(0, time1)
    24 ws.append(list_str2)
    25 
    26 # 如果你要在已经有的数据上进行修改,会自动覆盖掉,原有的数据
    27 # import datetime
    28 # ws['A2'] = datetime.datetime.now()
    29 
    30 # Save the file
    31 wb.save("sample.xlsx")


    在内存中处理一个工作簿:

    创建一个工作簿

    没有必要利用 openpyxl 先去创建一个文件系统上的文件然后才能开始使用。你只要导入工作簿类,然后开始使用它吧。

    >>> from openpyxl import Workbook
    >>> wb = Workbook()
    

    A workbook is always created with at least one worksheet. You can get it by using the  openpyxl.workbook.Workbook.active()  property

    一个工作簿被创建后,总会在里面默认创建一张工作表。你可以通过使用方法 openpyxl.workbook.Workbook.active() 来得到它。

     ws = wb.active
    

      默认状态下,函数 the _active_sheet_index property 的 index设置为0,除非你手动修改它的数值,否则的话,你用这个方法,只会拿到第一个工作表。

     1 @property
     2     def active(self):
     3         """Get the currently active sheet or None
     4 
     5         :type: :class:`openpyxl.worksheet.worksheet.Worksheet`
     6         """
     7         try:
     8             return self._sheets[self._active_sheet_index]
     9         except IndexError:
    10             pass
    11 
    12     @active.setter
    13     def active(self, value):
    14         """Set the active sheet"""
    15         self._active_sheet_index = value
    16 
    17     def create_sheet(self, title=None, index=None):
    18         """Create a worksheet (at an optional index).
    19 
    20         :param title: optional title of the sheet
    21         :type title: unicode
    22         :param index: optional position at which the sheet will be inserted
    23         :type index: int
    24 
    25         """
    26         if self.read_only:
    27             raise ReadOnlyWorkbookException('Cannot create new sheet in a read-only workbook')
    28 
    29         if self.write_only :
    30             new_ws = WriteOnlyWorksheet(parent=self, title=title)
    31         else:
    32             new_ws = Worksheet(parent=self, title=title)
    33 
    34         self._add_sheet(sheet=new_ws, index=index)
    35         return new_ws
    View Code

    可以通过 openpyxl.workbook.Workbook.create_sheet() 方法,创建工作表。

    wb.create_sheet("mysheet", 1)
    wss=wb.create_sheet()
    
    ws1 = wb.create_sheet("Mysheet111") # insert at the end (default)
    ws2 = wb.create_sheet("Mysheet222", 0) # insert at first position
    

    工作表的名字是自动命令。按照列表(Sheet, Sheet1, Sheet2, …)的内容,顺序命名。你也可以自定义工作表名字。

    ws.title = "New Title"
    

    默认情况下,包含此标题的选项卡的背景颜色为白色。您可以将此更改为为 sheet_properties 提供RRGGBB颜色代码。 tabColor 属性:

    ws.sheet_properties.tabColor = "1072BA"
    

     一旦你给一个工作表命名一个名字,你就可以把这个名字作为一个键去访问工作簿中的工作表:

    ws3 = wb["New Title"]
    

     你也可以通过方法 openpyxl.workbook.Workbook.sheetnames() 去遍历,查看工作簿中左右工作表的名称。

    查看工作表:

    print(wb.sheetnames)
    

      结果:

    ['Sheet', 'mystudent']

    遍历工作表:

    1 for sheetname in wb:
    2     print(sheetname.title)

    您可以在一个工作簿中创建工作表的副本:使用 openpyxl.workbook.Workbook.copy_worksheet() 方法

    >>> source = wb.active
    >>> target = wb.copy_worksheet(source)
    

      注意:1、只复制单元格(包括值、样式、超链接和注释)和某些工作表属性(包括维度、格式和属性)。所有其他工作簿/工作表属性都不会被复制-例如图像,图表。

                   2、您不能在工作簿之间复制工作表。如果工作簿以只读或只读模式打开,您也不能复制工作表。

    把玩数据

    操作单一单元格

    我们已经知道如何从外部进去工作表了。现在就可以对工作表里面的单元格内容进行各种操作了。

    单元格可以作为工作表的键直接访问

     c = ws['A4']
    

    这将返回A4大小的单元格,或者如果单元格还不存在,就创建一个单元格。值可以直接分配

    ws['A4'] = 4
    

    当然,你也可以通过方法 openpyxl.worksheet.Worksheet.cell() 去访问。该方法通过行和列的索引去访问,并且可以进行赋值操作。

    d = ws.cell(row=4, column=2, value=10)
    

    当一个工作表在内存中被创建的时候,他是不包含单元格。单元格只有在初次使用的时候,才会被创建。所以,当你访问一个不存在的单元格时,会报错。out of ranges

    注意:由于这个特性,在内存中,当单元格没有值得时候,而需要访问它们,我们可以利用滚动访问的方式替代直接访问的方式。 

    >>> for i in range(1,101):
    ...        for j in range(1,101):
    ...            ws.cell(row=i, column=j)
    

     以上代码会创建一个100*100的空白单元格。

    批量操作单元格

    可以使用切片访问单元格范围

    cell_range = ws['A1':'C2']
    

    行或列的范围可以类似地得到:

    >>> colC = ws['C']
    >>> col_range = ws['C:D']
    >>> row10 = ws[10]
    >>> row_range = ws[5:10]
    

    你也可以使用方法 openpyxl.worksheet.Worksheet.iter_rows() ,从左到右返回

    >>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
    ...    for cell in row:
    ...        print(cell)
    
    <Cell 'mystudent'.A1>
    <Cell 'mystudent'.B1>
    <Cell 'mystudent'.C1>
    <Cell 'mystudent'.A2>
    <Cell 'mystudent'.B2>
    <Cell 'mystudent'.C2>

    相似的方法 openpyxl.worksheet.Worksheet.iter_cols() 从上到下返回

    >>> for col in ws.iter_cols(min_row=1, max_col=3, max_row=2):
    ...     for cell in col:
    ...         print(cell)
    <Cell Sheet1.A1>
    <Cell Sheet1.A2>
    <Cell Sheet1.B1>
    <Cell Sheet1.B2>
    <Cell Sheet1.C1>
    <Cell Sheet1.C2>

    如果需要遍历文件的所有行或列,可以使用 openpyxpath .worksheet. worksheet. rows() 属性:

    >>> ws = wb.active
    >>> ws['C9'] = 'hello world'
    >>> tuple(ws.rows)
    ((<Cell Sheet.A1>, <Cell Sheet.B1>, <Cell Sheet.C1>),
    (<Cell Sheet.A2>, <Cell Sheet.B2>, <Cell Sheet.C2>),
    (<Cell Sheet.A3>, <Cell Sheet.B3>, <Cell Sheet.C3>),
    (<Cell Sheet.A4>, <Cell Sheet.B4>, <Cell Sheet.C4>),
    (<Cell Sheet.A5>, <Cell Sheet.B5>, <Cell Sheet.C5>),
    (<Cell Sheet.A6>, <Cell Sheet.B6>, <Cell Sheet.C6>),
    (<Cell Sheet.A7>, <Cell Sheet.B7>, <Cell Sheet.C7>),
    (<Cell Sheet.A8>, <Cell Sheet.B8>, <Cell Sheet.C8>),
    (<Cell Sheet.A9>, <Cell Sheet.B9>, <Cell Sheet.C9>))
    

    或者  openpyxl.worksheet.Worksheet.columns()  属性

    >>> tuple(ws.columns)
    ((<Cell Sheet.A1>,
    <Cell Sheet.A2>,
    <Cell Sheet.A3>,
    <Cell Sheet.A4>,
    <Cell Sheet.A5>,
    <Cell Sheet.A6>,
    ...
    <Cell Sheet.B7>,
    <Cell Sheet.B8>,
    <Cell Sheet.B9>),
    (<Cell Sheet.C1>,
    <Cell Sheet.C2>,
    <Cell Sheet.C3>,
    <Cell Sheet.C4>,
    <Cell Sheet.C5>,
    <Cell Sheet.C6>,
    <Cell Sheet.C7>,
    <Cell Sheet.C8>,
    <Cell Sheet.C9>))
    

    数据存储

    一旦我们通过 openpyxl.cell.Cell ,拿到单元格,我们就可以给它赋值了。

    >>> c.value = 'hello, world'
    >>> print(c.value)
    'hello, world'
    
    >>> d.value = 3.14
    >>> print(d.value)
    3.14
    
     1 Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
     2 Type "copyright", "credits" or "license()" for more information.
     3 >>> import openpyxl
     4 >>> wb=openpyxl.Workbook()
     5 >>> ws=wb.create_sheet()
     6 >>> ws.title="mystudent"
     7 >>> ws.sheet_properties.tabColor="1072BA"
     8 >>> c=ws['A4']
     9 >>> d=ws.cell(row=4,column=2,value=10)
    10 >>> c.value="中国"
    11 >>> c
    12 <Cell 'mystudent'.A4>
    13 >>> print(c.value)
    14 中国
    15 >>> d.value
    16 10
    17 >>> d.value=3.1415926
    18 >>> print(d.value)
    19 3.1415926
    20 >>> 
    View Code

    你也可以使用类型和格式。 注意::guess_types=True  测试使用,暂时用不了。会报错。没有这个参数。python37

     1 >>> wb = Workbook(guess_types=True)
     2 >>> c.value = '12%'
     3 >>> print(c.value)
     4 0.12
     5 
     6 >>> import datetime
     7 >>> d.value = datetime.datetime.now()
     8 >>> print d.value
     9 datetime.datetime(2010, 9, 10, 22, 25, 18)
    10 
    11 >>> c.value = '31.50'
    12 >>> print(c.value)
    13 31.5

    保存文件

     保存工作簿的最简单和最安全的方法是使用 openpyxl.workbook.Workbook 对象提供的 openpyxl.workbook.Workbook.save() 方法。

    >>> wb = Workbook()
    >>> wb.save('balances.xlsx')
    

      注意:如果文件名为已有的文件名,此操作将在没有任何警告的情况下覆盖现有文件。

    您可以指定属性template=True,以将工作簿保存为模板:

    >>> wb = load_workbook('document.xlsx')
    >>> wb.template = True
    >>> wb.save('document_template.xltx')
    

    或将此属性设置为False(默认),保存为文档:

    >>> wb = load_workbook('document_template.xltx')
    >>> wb.template = False
    >>> wb.save('document.xlsx', as_template=False)
    

      您应该监视数据属性和文档扩展,以便在文档模板中保存文档,反之亦然,否则结果表引擎无法打开文档。

    接下的操作会保存失败:

    >>> wb = load_workbook('document.xlsx')
    >>> # Need to save with the extension *.xlsx
    >>> wb.save('new_document.xlsm')
    >>> # MS Excel can't open the document
    >>>
    >>> # or
    >>>
    >>> # Need specify attribute keep_vba=True
    >>> wb = load_workbook('document.xlsm')
    >>> wb.save('new_document.xlsm')
    >>> # MS Excel will not open the document
    >>>
    >>> # or
    >>>
    >>> wb = load_workbook('document.xltm', keep_vba=True)
    >>> # If we need a template document, then we must specify extension as *.xltm.
    >>> wb.save('new_document.xlsm')
    >>> # MS Excel will not open the document

    加载文件:

    与编写相同的方法是,可以导入 openpyxx .load_workbook() 来打开现有的工作簿:

    >>> from openpyxl import load_workbook
    >>> wb2 = load_workbook('test.xlsx')
    >>> print wb2.sheetnames
    ['Sheet2', 'New Title', 'Sheet1']
    

    简单操作到此结束。

  • 相关阅读:
    Hbase 笔记(4) 客户端API高级性能
    Hbase 笔记(3) 客户端API基础
    Hbase 笔记(2) 安装
    HBase 笔记(1) 简介
    Global 和 Local 索引。
    Phoenix Tips (14) mutable 和 immutable 表区别
    Phoenix Tips (13) 统计收集
    Phoenix Tips (12) 跟踪 Tracing
    Phoenix Tips (11) Skip Scan
    Phoenix Tips (10) 分页查询
  • 原文地址:https://www.cnblogs.com/Mengchangxin/p/9496275.html
Copyright © 2011-2022 走看看