51Testing软件测试论坛

标题: 教您掌握openpyxl神操作之Python! [打印本页]

作者: lsekfe    时间: 2022-8-11 09:55
标题: 教您掌握openpyxl神操作之Python!
今天给大家分享一篇用openpyxl操作Excel的文章
  各种数据需要导入Excel?多个Excel要合并?目前,Python处理Excel文件有很多库,openpyxl算是其中功能和性能做的比较好的一个。接下来我将为大家介绍各种Excel操作。
  1、打开Excel文件
  新建一个Excel文件
  1. >>> from openpyxl import Workbook
  2.   >>> wb = Workbook()
复制代码
打开现有Excel文件

  1. >>> from openpyxl import load_workbook
  2.   >>> wb2 = load_workbook('test.xlsx')
复制代码
打开大文件时,根据需求使用只读或只写模式减少内存消耗。

  1. wb = load_workbook(filename='large_file.xlsx', read_only=True)
  2.   wb = Workbook(write_only=True)
复制代码
2、获取、创建工作表
  获取当前活动工作表:
  1. >>> ws = wb.active
复制代码
创建新的工作表:
  1. >>> ws1 = wb.create_sheet("Mysheet") # insert at the end (default)
  2.      # or
  3.      >>> ws2 = wb.create_sheet("Mysheet", 0) # insert at first position
  4.      # or
  5.      >>> ws3 = wb.create_sheet("Mysheet", -1) # insert at the penultimate position
复制代码
 使用工作表名字获取工作表:
  1. >>> ws3 = wb["New Title"]
复制代码
获取所有的工作表名称:
  1. >>> print(wb.sheetnames)
  2.      ['Sheet2', 'New Title', 'Sheet1']
  3.   使用for循环遍历所有的工作表:
  4.      >>> for sheet in wb:
  5.      ...     print(sheet.title)
复制代码
3、保存
  保存到流中在网络中使用:
  1. >>> from tempfile import NamedTemporaryFile
  2.      >>> from openpyxl import Workbook
  3.      >>> wb = Workbook()
  4.      >>> with NamedTemporaryFile() as tmp:
  5.              wb.save(tmp.name)
  6.              tmp.seek(0)
  7.              stream = tmp.read()
  8.   保存到文件:
  9.      >>> wb = Workbook()
  10.      >>> wb.save('balances.xlsx')
  11.   保存为模板:
  12.      >>> wb = load_workbook('document.xlsx')
  13.      >>> wb.template = True
  14.      >>> wb.save('document_template.xltx')
复制代码
4、单元格
  单元格位置作为工作表的键直接读取:
  1.  >>> c = ws['A4']
复制代码
为单元格赋值:
  1.  >>> ws['A4'] = 4
  2.      >>> c.value = 'hello, world'
复制代码
多个单元格 可以使用切片访问单元格区域:
  1.  >>> cell_range = ws['A1':'C2']
复制代码
使用数值格式:
  1.  >>> # set date using a Python datetime
  2.      >>> ws['A1'] = datetime.datetime(2010, 7, 21)
  3.      >>>
  4.   >>> ws['A1'].number_format
  5.      'yyyy-mm-dd h:mm:ss'
复制代码
使用公式:
  1. >>> # add a simple formula
  2.      >>> ws["A1"] = "=SUM(1, 1)"
复制代码
合并单元格时,除左上角单元格外,所有单元格都将从工作表中删除:
  1. >>> ws.merge_cells('A2:D2')
  2.      >>> ws.unmerge_cells('A2:D2')
  3.      >>>
  4.   >>> # or equivalently
  5.      >>> ws.merge_cells(start_row=2, start_column=1, end_row=4, end_column=4)
  6.      >>> ws.unmerge_cells(start_row=2, start_column=1, end_row=4, end_column=4)
复制代码
5、行、列
  可以单独指定行、列、或者行列的范围:
  1. >>> colC = ws['C']
  2.      >>> col_range = ws['C:D']
  3.      >>> row10 = ws[10]
  4.      >>> row_range = ws[5:10]
复制代码
可以使用Worksheet.iter_rows()方法遍历行:
  1. >>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
  2.      ...    for cell in row:
  3.      ...        print(cell)
  4.      <Cell Sheet1.A1>
  5.      <Cell Sheet1.B1>
  6.      <Cell Sheet1.C1>
  7.      <Cell Sheet1.A2>
  8.      <Cell Sheet1.B2>
  9.      <Cell Sheet1.C2>
复制代码
同样的Worksheet.iter_cols()方法将遍历列:
  1. >>> for col in ws.iter_cols(min_row=1, max_col=3, max_row=2):
  2.      ...     for cell in col:
  3.      ...         print(cell)
  4.      <Cell Sheet1.A1>
  5.      <Cell Sheet1.A2>
  6.      <Cell Sheet1.B1>
  7.      <Cell Sheet1.B2>
  8.      <Cell Sheet1.C1>
  9.      <Cell Sheet1.C2>
复制代码
遍历文件的所有行或列,可以使用Worksheet.rows属性:
  1. >>> ws = wb.active
  2.      >>> ws['C9'] = 'hello world'
  3.      >>> tuple(ws.rows)
  4.      ((<Cell Sheet.A1>, <Cell Sheet.B1>, <Cell Sheet.C1>),
  5.      (<Cell Sheet.A2>, <Cell Sheet.B2>, <Cell Sheet.C2>),
  6.      (<Cell Sheet.A3>, <Cell Sheet.B3>, <Cell Sheet.C3>),
  7.      (<Cell Sheet.A4>, <Cell Sheet.B4>, <Cell Sheet.C4>),
  8.      (<Cell Sheet.A5>, <Cell Sheet.B5>, <Cell Sheet.C5>),
  9.      (<Cell Sheet.A6>, <Cell Sheet.B6>, <Cell Sheet.C6>),
  10.      (<Cell Sheet.A7>, <Cell Sheet.B7>, <Cell Sheet.C7>),
  11.      (<Cell Sheet.A8>, <Cell Sheet.B8>, <Cell Sheet.C8>),
  12.      (<Cell Sheet.A9>, <Cell Sheet.B9>, <Cell Sheet.C9>))
复制代码
或Worksheet.columns属性:
  1.  >>> tuple(ws.columns)
  2.      ((<Cell Sheet.A1>,
  3.      <Cell Sheet.A2>,
  4.      <Cell Sheet.A3>,
  5.      <Cell Sheet.A4>,
  6.      <Cell Sheet.A5>,
  7.      <Cell Sheet.A6>,
  8.      ...
  9.      <Cell Sheet.B7>,
  10.      <Cell Sheet.B8>,
  11.      <Cell Sheet.B9>),
  12.      (<Cell Sheet.C1>,
  13.      <Cell Sheet.C2>,
  14.      <Cell Sheet.C3>,
  15.      <Cell Sheet.C4>,
  16.      <Cell Sheet.C5>,
  17.      <Cell Sheet.C6>,
  18.      <Cell Sheet.C7>,
  19.      <Cell Sheet.C8>,
  20.      <Cell Sheet.C9>))
复制代码
使用Worksheet.append()或者迭代使用Worksheet.cell()新增一行数据:
  1. >>> for row in range(1, 40):
  2.      ...     ws1.append(range(600))
  3.      >>> for row in range(10, 20):
  4.      ...     for col in range(27, 54):
  5.      ...         _ = ws3.cell(column=col, row=row, value="{0}".format(get_column_letter(col)))
复制代码
插入操作比较麻烦。可以使用Worksheet.insert_rows()插入一行或几行:
  1.  >>> from openpyxl.utils import get_column_letter
  2.        >>> ws.insert_rows(7)  
  3.       >>> row7 = ws[7]
  4.       >>> for col in range(27, 54):
  5.      ...         _ = ws3.cell(column=col, row=7, value="{0}".format(get_column_letter(col)))
  6.   Worksheet.insert_cols()操作类似。Worksheet.delete_rows()和Worksheet.delete_cols()用来批量删除行和列。
复制代码
6、只读取值
  使用Worksheet.values属性遍历工作表中的所有行,但只返回单元格值:
  1. for row in ws.values:
  2.         for value in row:
  3.           print(value)
复制代码
Worksheet.iter_rows()和Worksheet.iter_cols()可以设置values_only参数来仅返回单元格的值:
  1. >>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2, values_only=True):
  2.      ...   print(row)
  3.      (None, None, None)
  4.       (None, None, None)
复制代码














欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) Powered by Discuz! X3.2