Python openpyxl module is a native library to work with excel files. We can read excel files as well as write excel files.

Python openpyxl模块是使用excel文件的本机库。 我们可以读取excel文件,也可以写入excel文件。

1)安装Openpyxl模块 (1) Installing Openpyxl Module)

We can install openpyxl module using the PIP command.

我们可以使用PIP命令安装openpyxl模块。

$ pip install openpyxl

Pip Install Openpyxl

点安装Openpyxl

2)使用openpyxl读取Excel文件 (2) Reading Excel File using openpyxl)

I have created a sample excel file (records.xlsx) with three sheets. The data is present in the first two sheets.

我用三张纸创建了一个示例excel文件(records.xlsx)。 数据显示在前两页中。

Openpyxl Example Excel Sheet

Openpyxl Excel表格示例

We will use this excel file to look at some examples to read data from the excel sheet.

我们将使用此excel文件查看一些示例以从excel表中读取数据。

1.从Excel文件获取工作表名称 (1. Getting Sheet Names from the Excel File)

import openpyxlexcel_file = openpyxl.load_workbook('records.xlsx')# sheet names
print(excel_file.sheetnames)

Output:

输出:

['Employees', 'Cars', 'Numbers']

The sheetnames variable returns the list of the names of worksheets in the workbook. The names are returned in the order of the worksheets in the excel file.

sheetnames变量返回工作簿中工作表名称的列表。 名称按照excel文件中工作表的顺序返回。

2.从Excel文件获取特定工作表 (2. Getting Specific Sheet from the Excel File)

We can access a specific worksheet using the index variable with the workbook object.

我们可以使用带有工作簿对象的index变量来访问特定的工作表。

employees_sheet = excel_file['Employees']print(type(excel_file))
print(type(employees_sheet))currently_active_sheet = excel_file.active

Output:

输出:

<class 'openpyxl.workbook.workbook.Workbook'>
<class 'openpyxl.worksheet.worksheet.Worksheet'>

If you want to access the currently active sheet, use the active property of the workbook.

如果要访问当前活动的工作表,请使用工作簿的active属性。

3.从Excel工作表中读取单元格值 (3. Reading a Cell Value from the Excel Sheet)

There are two ways to get a cell value from the excel sheet. We can get the Cell object using the cell() function or we can get it using the index of the cell.

有两种方法可以从Excel工作表中获取单元格值。 我们可以使用cell()函数获取Cell对象,也可以使用单元格的索引获取它。

cell_obj = employees_sheet.cell(row=1, column=1)
print(type(cell_obj))
print(f'Employees[A1]={cell_obj.value}')# second way
print(f'Employees[A1]={employees_sheet["A1"].value}')

Output:

输出:

<class 'openpyxl.cell.cell.Cell'>
Employees[A1]=EmpID
Employees[A1]=EmpID

4. Excel工作表中的行和列总数 (4. Total Number of Rows and Columns in the Excel Sheet)

We can get the total number of rows and columns using the max_row and max_column properties of the worksheet.

我们可以使用工作表的max_rowmax_column属性获取行和列的max_row

print(f'Total Rows = {employees_sheet.max_row} and Total Columns = {employees_sheet.max_column}')

Output:

输出:

Total Rows = 4 and Total Columns = 3

5.打印Excel工作表的标题行 (5. Printing Header Row of the Excel Sheet)

header_cells_generator = employees_sheet.iter_rows(max_row=1)for header_cells_tuple in header_cells_generator:for i in range(len(header_cells_tuple)):print(header_cells_tuple[i].value)

Output:

输出:

EmpID
EmpName
EmpRole

The iter_rows() function generates cells from the worksheet, by row. We can use it to get the cells from a specific row.

iter_rows()函数从工作表中按行生成单元格。 我们可以使用它来获取特定行中的单元格。

6.打印列中的所有值 (6. Printing all the values from a column)

for x in range(1, employees_sheet.max_row+1):print(employees_sheet.cell(row=x, column=1).value)

Output:

输出:

EmpID
1
2
3

7.从一行中打印所有值 (7. Printing all the values from a row)

for x in range(1, employees_sheet.max_column+1):print(employees_sheet.cell(row=2, column=x).value)

Output:

输出:

1
Pankaj
CEO

8.从Excel工作表中读取单元格的范围 (8. Reading Range of Cells from the Excel Sheet)

We can pass the range of cells to read multiple cells at a time.

我们可以传递单元格的范围以一次读取多个单元格。

cells = employees_sheet['A2':'C3']for id, name, role in cells:print(f'Employee[{id.value}, {name.value}, {role.value}]')

Output:

输出:

Employee[1, Pankaj, CEO]
Employee[2, David Lee, Editor]

9.按行迭代单元格 (9. Iterating Cells by Rows)

for row in employees_sheet.iter_rows(min_row=2, min_col=1, max_row=4, max_col=3):for cell in row:print(cell.value, end="|")print("")

Output:

输出:

1|Pankaj|CEO|
2|David Lee|Editor|
3|Lisa Ray|Author|

The arguments passed to the iter_rows() function creates the two-dimensional table from which the values are read, by row. In this example, the values are read between A2 and C4.

传递给iter_rows()函数的参数创建一个二维表,从该表中按行读取值。 在此示例中,在A2和C4之间读取值。

10.按列迭代单元格 (10. Iterating Cells by Columns)

for col in employees_sheet.iter_cols(min_row=2, min_col=1, max_row=4, max_col=3):for cell in col:print(cell.value, end="|")print("")

Output:

输出:

1|2|3|
Pankaj|David Lee|Lisa Ray|
CEO|Editor|Author|

The iter_cols() function is same as iter_rows() except that the values are read column-wise.

iter_cols()函数与iter_rows()相同,只不过是按列读取值。

3)使用openpyxl编写Excel文件 (3) Writing Excel File using openpyxl)

In this section, we will look into some examples of writing excel files and cell data.

在本节中,我们将研究一些编写excel文件和单元格数据的示例。

1.使用openpyxl编写Excel文件 (1. Writing Excel File using openpyxl)

from openpyxl import Workbook
import datetimeexcel_file = Workbook()
excel_sheet = excel_file.create_sheet(title='Holidays 2019', index=0)# creating header row
excel_sheet['A1'] = 'Holiday Name'
excel_sheet['B1'] = 'Holiday Description'
excel_sheet['C1'] = 'Holiday Date'# adding data
excel_sheet['A2'] = 'Diwali'
excel_sheet['B2'] = 'Biggest Indian Festival'
excel_sheet['C2'] = datetime.date(year=2019, month=10, day=27).strftime("%m/%d/%y")excel_sheet['A3'] = 'Christmas'
excel_sheet['B3'] = 'Birth of Jesus Christ'
excel_sheet['C3'] = datetime.date(year=2019, month=12, day=25).strftime("%m/%d/%y")# save the file
excel_file.save(filename="Holidays.xlsx")

Output:

输出:

Openpyxl Write Excel File

Openpyxl写入Excel文件

2.更新单元格值 (2. Updating a Cell value)

We can either use the index of the cell or use the cell object to set the value. Let’s change some values in the excel file created in the last example.

我们可以使用单元格的索引,也可以使用单元格对象来设置值。 让我们更改在上一个示例中创建的excel文件中的一些值。

import openpyxlexcel_file = openpyxl.load_workbook('Holidays.xlsx')
excel_sheet = excel_file['Holidays 2019']# using index
excel_sheet['A2'] = 'Deepawali'# using cell object
excel_sheet.cell(row=2, column=2).value = 'Biggest Indian Festival for Hindus'excel_file.save('Holidays.xlsx')

Output:

输出:

Openpyxl Update Cell Value

Openpyxl更新单元格值

3.将多个值附加到Excel工作表 (3. Appending Multiple Values to the Excel Sheet)

We can use the append() function to add a sequence of values to the bottom of the worksheet.

我们可以使用append()函数在工作表的底部添加一系列值。

holiday_rows = (('Black Friday', 'Fourth Thursday of November, Shopping Day', '11/29/19'),('Holi', 'Festival of Colors', '3/20/19')
)for row in holiday_rows:excel_sheet.append(row)excel_file.save('Holidays.xlsx')

Output:

输出:

Openpyxl Append Multiple Rows To Excel File

Openpyxl将多行追加到Excel文件

4)从Excel工作表中删除行和列 (4) Deleting Rows and Columns from the Excel Sheet)

We can use the delete_cols() and delete_rows() functions to delete columns and rows from the excel sheet.

我们可以使用delete_cols()和delete_rows()函数从excel工作表中删除列和行。

import openpyxlexcel_file = openpyxl.load_workbook('Holidays.xlsx')
excel_sheet = excel_file['Holidays 2019']# delete column
excel_sheet.delete_cols(idx=2)  # B=2# delete row
excel_sheet.delete_rows(idx=2, amount=2)  # rows 2,3 are deletedexcel_file.save('Holidays.xlsx')

The idx parameter provides the index of the rows and columns to delete. If we want to delete multiple adjacent rows and columns, we can provide the amount argument.

idx参数提供要删除的行和列的索引。 如果要删除多个相邻的行和列,可以提供amount参数。

5)结论 (5) Conclusion)

Python openpyxl module is a perfect choice to work with excel sheets. We can also add images to the excel sheet by using the pillow library with it. But, it doesn’t guard us against quadratic blowup or billion laughs XML attacks. So, if you are getting values from the user and saving it, then try to validate and sanitize it.

Python openpyxl模块是使用excel工作表的理想选择。 我们还可以通过使用枕头库将图像添加到excel工作表中。 但是,它不能防止我们遭受二次爆炸或数十亿次XML攻击。 因此,如果您要从用户那里获取并保存值,请尝试对其进行验证和消毒。

6)进一步阅读 (6) Further Readings)

  • Pandas read_excel() – Reading Excel File in Python熊猫read_excel()–用Python读取Excel文件
  • Python ModulesPython模块
  • Python TutorialPython教程

7)参考 (7) References)

  • PyPI.org DocsPyPI.org文件
  • BitBucket Source CodeBitBucket源代码

翻译自: https://www.journaldev.com/33325/openpyxl-python-read-write-excel-files

Openpyxl:读取/写入Excel文件的Python模块相关推荐

  1. python读写xlsx文件_python读写Excel文件--使用xlrd模块读取,xlwt模块写入

    一.安装xlrd模块和xlwt模块 1. 下载xlrd模块和xlwt模块 到python官网http://pypi.python.org/pypi/xlrd下载模块.下载的文件例如:xlrd-0.9. ...

  2. python 通过openpyxl来操作Excel文件(一 ):读取Excel文件

    这篇文章讲python 通过openpyxl来读取Excel文件 不清楚怎么通过openpyxl来写入Excel文件的小伙伴可以看我另一篇文章 传送门python 通过openpyxl来操作Excel ...

  3. python 通过openpyxl来操作Excel文件(二 ):写入Excel文件

    这篇文章讲python 通过openpyxl来写入Excel文件,不清楚python怎么读取Excel文件的小伙伴可以去看下我的另一篇文章 传送门https://blog.csdn.net/i_cof ...

  4. xlsxwriter写行合并_XlsxWriter写入excel文件

    XlsxWriter写入excel文件 唐黎琦 [摘要] 在日常开发中,我们经常会遇到需要将数据导出为excel的场景,XlsxWriter作为专门写入excel文件的python库,对excel文件 ...

  5. python读取excel内容和写入_Python读取和写入Excel文件

    制作Excel表 常用方法说明 Workbook类 Workbook类创建一个XlswWrite的Workbook对象,相当于创建一个excel表 And_worksheet()用来创建工作表,默认为 ...

  6. Pymediainfo读取文件夹视频长度并写入Excel文件(openpyxl)

    Pymediainfo读取文件夹视频长度并写入excel文件(openpyxl) 导入使用的module 路径设置以及初始化 获取全部文件名称与文件大小 获取视频详细信息并存储 时间统计并得到总秒数及 ...

  7. python之读取、写入 excel 文件

    本文主要讨论如何使用 python 读取.写入 excel 文件.如有表述不当之处欢迎批评指正.欢迎任何形式的转载,但请务必注明出处. 目录 1. 引言 2. 读取 Excel 文件 3. 写入 Ex ...

  8. Python读取和写入excel文件

    Hello!今天我们来聊一下python读取和写入文件的操作. 在进行数据分析和数据挖掘等等有关数据的操作中,我们一般都会碰到python与excel的具体操作.从excel中读取数据出来进行分析,清 ...

  9. python xlwt写入数据超过范围限制_用xlrd包读取Excel文件-尽量不用xlwt包写入Excel文件最多能支持65536行数据。...

    1. 引有包 import xlrd1 打开文件 data = good_ivy = xlrd.open_workbook(r'商品库存.xls')1 2 获取你要打开的sheet文件 # table ...

最新文章

  1. 洛谷 P1387 最大正方形
  2. NoSQL, Clojure
  3. MySQL 高级 —— 索引实现的思考
  4. Java 简单五子棋程序的实现
  5. 这个80后靠王者荣耀赚到93亿身家
  6. 据说学编程的计算这题不超1分钟!
  7. 关于数据分析师的4个你问我答,你曾有过这些困扰吗?
  8. linux 下 sudo 指令不需要输入密码的配置
  9. hao916,hao123,2345.com浏览器劫持-分析与清除
  10. 集合竞价与连续竞价02
  11. ubuntu18.04未发现wifi适配器,安装wifi无线网卡驱动-RTL8822BE、RTL8822CE、RTL8821CE、RTL8723DE
  12. 快手裁员30%,大部分年薪超100万!揭露职场真相:思考的深度,决定职场的高度...
  13. Java 复习之多线程
  14. 2022-2028年中国5G 汽车产业应用市场竞争策略及未来发展潜力报告
  15. elasticsearch--拼音转换插件
  16. 前端项目搭建部署全流程(一):搭建React项目
  17. KITTI数据集测试 - 3 calib 相机参数
  18. 被指将赴美上市的雪球:累计融资近3亿美元,股东股权已全部出质
  19. 在岸人民币和离岸人民币的区别
  20. 9.0 桌面应用QuickStep

热门文章

  1. gvim的常用编辑快捷键
  2. DataGrid与SQL Server 2000数据绑定
  3. [转载] python __import__ 搜索路径详解
  4. 总结下MySql优化。防止数据灾难的发生。
  5. Python 模块安装失败
  6. gitlab git 安装
  7. python第八十八天----dom js
  8. android 自动更新
  9. sscanf函数详解
  10. iOS6中旋转的略微改变