


Today I will share with you an article about using openpyxl to operate Excel.
Need to import various data into Excel? Want to merge multiple Excels? Currently, there are many libraries for Python to process Excel files, and openpyxl is one of them with better functions and performance. Next, I will introduce various Excel operations to you.
1. Open Excel file
Create a new Excel file
>>> from openpyxl import Workbook >>> wb = Workbook()
Open an existing Excel file
>>> from openpyxl import load_workbook >>> wb2 = load_workbook('test.xlsx')
When opening a large file , use read-only or write-only mode according to needs to reduce memory consumption.
wb = load_workbook(filename='large_file.xlsx', read_only=True) wb = Workbook(write_only=True)
2. Get and create worksheet
Get the current active worksheet:
>>> ws = wb.active
Create a new worksheet:
>>> 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
Get the worksheet using the worksheet name:
>>> ws3 = wb["New Title"]
Get all the worksheet names:
>>> print(wb.sheetnames) ['Sheet2', 'New Title', 'Sheet1'] 使用for循环遍历所有的工作表: >>> for sheet in wb: ... print(sheet.title)
3. Save
Save to the stream in the network Use:
>>> 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')
4, cell
The cell position is used as the key of the worksheet to read directly:
>>> c = ws['A4']
Assign value to the cell:
>>> ws['A4'] = 4 >>> c.value = 'hello, world'
Multiple cells can use slicing to access the cell range:
>>> cell_range = ws['A1':'C2']
Use numerical format:
>>> # set date using a Python datetime >>> ws['A1'] = datetime.datetime(2010, 7, 21) >>> >>> ws['A1'].number_format 'yyyy-mm-dd h:mm:ss'
Use formula:
>>> # add a simple formula >>> ws["A1"] = "=SUM(1, 1)"
When merging cells , except the upper left corner cell, all cells will be deleted from the worksheet:
>>> 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)
5, rows, columns
You can specify rows, columns, or ranges of rows and columns individually :
>>> colC = ws['C'] >>> col_range = ws['C:D'] >>> row10 = ws[10] >>> row_range = ws[5:10]
You can use the Worksheet.iter_rows() method to iterate over the 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>
The same Worksheet.iter_cols() method will iterate over the columns:
>>> 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>
Iterate over all rows of the file or columns, you can use the Worksheet.rows property:
>>> ws = wb.active >>> ws['C9'] = 'hello world' >>> tuple(ws.rows) ((, | , | ), ( | , | , | ), ( | , | , | ), ( | , | , | ), ( | , | , | ), ( | , | , | ), ( | , | , | ), ( | , | , | ), ( | , | , | )) |
or the Worksheet.columns property:
>>> 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>))
Use Worksheet.append() or iteratively use Worksheet.cell() to add a row of data:
>>> 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)))
The insertion operation is more troublesome. You can use Worksheet.insert_rows() to insert one or several 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()用来批量删除行和列。
6. Read only the values
Use the Worksheet.values property to traverse all rows in the worksheet, but only Return the cell value:
for row in ws.values: for value in row: print(value)
Worksheet.iter_rows() and Worksheet.iter_cols() can set the values_only parameter to return only the cell value:
>>> 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)
The above is the detailed content of Python office automation, master openpyxl operation in five minutes!. For more information, please follow other related articles on the PHP Chinese website!

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

Notepad++7.3.1
Easy-to-use and free code editor

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.