关于python:Python办公软件自动化5分钟掌握openpyxl操作

2次阅读

共计 4754 个字符,预计需要花费 12 分钟才能阅读完成。

明天给大家分享一篇用 openpyxl 操作 Excel 的文章。

各种数据须要导入 Excel?多个 Excel 要合并?目前,Python 解决 Excel 文件有很多库,openpyxl 算是其中性能和性能做的比拟好的一个。接下来我将为大家介绍各种 Excel 操作。

关上 Excel 文件

新建一个 Excel 文件

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

关上现有 Excel 文件

    >>> from openpyxl import load_workbook
    >>> wb2 = load_workbook('test.xlsx')

关上大文件时,依据需要应用只读或只写模式缩小内存耗费。

wb = load_workbook(filename='large_file.xlsx', read_only=True)

wb = Workbook(write_only=True)

获取、创立工作表

获取以后流动工作表:

    >>> ws = wb.active

创立新的工作表:

    >>> ws1 = wb.create_sheet("Mysheet") # insert at the end (default)
    # or
    >>> ws2 = wb.create_sheet("Mysheet", 0) # insert at first position
    # or
    >>> ws3 = wb.create_sheet("Mysheet", -1) # insert at the penultimate position

应用工作表名字获取工作表:

    >>> ws3 = wb["New Title"]

获取所有的工作表名称:

    >>> print(wb.sheetnames)
    ['Sheet2', 'New Title', 'Sheet1']
应用 for 循环遍历所有的工作表:>>> for sheet in wb:
    ...     print(sheet.title)

保留

保留到流中在网络中应用:

    >>> from tempfile import NamedTemporaryFile
    >>> from openpyxl import Workbook
    >>> wb = Workbook()
    >>> with NamedTemporaryFile() as tmp:
            wb.save(tmp.name)
            tmp.seek(0)
            stream = tmp.read()
保留到文件:>>> wb = Workbook()
    >>> wb.save('balances.xlsx')
保留为模板:>>> wb = load_workbook('document.xlsx')
    >>> wb.template = True
    >>> wb.save('document_template.xltx')

单元格

单元格地位作为工作表的键间接读取:

    >>> c = ws['A4']

为单元格赋值:

    >>> ws['A4'] = 4
    >>> c.value = 'hello, world'

多个单元格 能够应用切片拜访单元格区域:

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

应用数值格局:

    >>> # set date using a Python datetime
    >>> ws['A1'] = datetime.datetime(2010, 7, 21)
    >>>
    >>> ws['A1'].number_format
    'yyyy-mm-dd h:mm:ss'

应用公式:

    >>> # add a simple formula
    >>> ws["A1"] = "=SUM(1, 1)"

合并单元格时,除左上角单元分外,所有单元格都将从工作表中删除:

    >>> ws.merge_cells('A2:D2')
    >>> ws.unmerge_cells('A2:D2')
    >>>
    >>> # or equivalently
    >>> ws.merge_cells(start_row=2, start_column=1, end_row=4, end_column=4)
    >>> ws.unmerge_cells(start_row=2, start_column=1, end_row=4, end_column=4) 

行、列

能够独自指定行、列、或者行列的范畴:

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

能够应用 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 Sheet1.A1>
    <Cell Sheet1.B1>
    <Cell Sheet1.C1>
    <Cell Sheet1.A2>
    <Cell Sheet1.B2>
    <Cell Sheet1.C2>

同样的 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>

遍历文件的所有行或列,能够应用 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>))

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

应用 Worksheet.append() 或者迭代应用 Worksheet.cell() 新增一行数据:

    >>> for row in range(1, 40):
    ...     ws1.append(range(600))

    >>> for row in range(10, 20):
    ...     for col in range(27, 54):
    ...         _ = ws3.cell(column=col, row=row, value="{0}".format(get_column_letter(col)))

插入操作比拟麻烦。能够应用 Worksheet.insert_rows() 插入一行或几行:

     >>> from openpyxl.utils import get_column_letter
     >>> ws.insert_rows(7) 
     >>> row7 = ws[7]
     >>> for col in range(27, 54):
    ...         _ = ws3.cell(column=col, row=7, value="{0}".format(get_column_letter(col)))

Worksheet.insert_cols()操作相似。Worksheet.delete_rows()Worksheet.delete_cols() 用来批量删除行和列。

只读取值

应用 Worksheet.values 属性遍历工作表中的所有行,但只返回单元格值:

    for row in ws.values:
       for value in row:
         print(value)

Worksheet.iter_rows()Worksheet.iter_cols() 能够设置 values_only 参数来仅返回单元格的值:

    >>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2, values_only=True):
    ...   print(row)
    (None, None, None)
    (None, None, None)

以上就是本次分享的所有内容,如果你感觉文章还不错,欢送关注公众号:Python 编程学习圈,每日干货分享,发送“J”还可支付大量学习材料,内容笼罩 Python 电子书、教程、数据库编程、Django,爬虫,云计算等等。或是返回编程学习网,理解更多编程技术常识。

正文完
 0