首页 > 编程语言 >python中的openxl模块

python中的openxl模块

时间:2023-03-15 19:12:28浏览次数:63  
标签:xlsx sheet openpyxl python ## 模块 active openxl data

openxl模块只能用于对xlsx格式的Excel文件进行处理,对于较早的xls格式无法进行处理。

1.安装

pip install openxl

2.导入

import openxl

3.创建新的 .xlsx 文件

import openpyxl
 
## CREATING XLSX FILE
 
## initializing the xlsx
xlsx = openpyxl.Workbook()
 
## creating an active sheet to enter data
sheet = xlsx.active  # 查看当前使用的是哪个sheet
 
## entering data into the A1 and B1 cells in the sheet
sheet['A1'] = 'Studytonight'
sheet['B1'] = 'A Programming Site'
 
## saving the xlsx file using 'save' method
xlsx.save('sample.xlsx')

以上程序在当前工作目录中创建了一个名为sample.xlsx的.xlsx文件。

 

 写入单元格

import openpyxl
 
## initializing the xlsx
xlsx = openpyxl.Workbook()
 
## creating an active sheet to enter data
sheet = xlsx.active
 
## entering data into the cells using 1st method
sheet['A1'] = 'Studytonight'
sheet['B2'] = 'Cell B2'
 
## entering data into the cells using 2nd method
sheet.cell(row = 1, column = 2).value = 'A Programming Site' 
sheet.cell(row = 2, column = 1).value = "B1" 
 
## saving the xlsx file using 'save' method
xlsx.save('write_to_cell.xlsx')

我们将获得具有行和列值的 cell()。获取单元格后,使用 value 变量为其赋值。

将数据附加到 .xlsx 文件

append() 方法用于将数据附加到任何单元格。示例:

import openpyxl
 
## initializing the xlsx
xlsx = openpyxl.Workbook()
 
## creating an active sheet to enter data
sheet = xlsx.active
 
## creating data to append
data = [
         [1, 2, 3],
         [4, 5, 6],
         [7, 8, 9],
         [10, 11, 12]
       ]
 
## appending row by row to the sheet
for row in data:
    ## append method is used to append the data to a cell
    sheet.append(row)
 
## saving the xlsx file using 'save' method
xlsx.save('appending.xlsx')

 

 通过上述程序,在 .xlsx 文件中附加了 4 行和 3 列值,还可以使用 tuples 或任何可迭代对象来代替列表。

从单元格中读取数据

import openpyxl
 
## opening the previously created xlsx file using 'load_workbook()' method
xlsx = openpyxl.load_workbook('sample.xlsx')  # 打开存在的文件
 
## getting the sheet to active
sheet = xlsx.active
 
## getting the reference of the cells which we want to get the data from
name = sheet['A1']
tag = sheet.cell(row = 1, column = 2)
 
## printing the values of cells
print(name.value)
print(tag.value)
Studytonight
A Programming Site

从多个单元格读取数据

现在我们将使用appending.xlsx文件来读取数据,包含从1到12的数值,以 4 行和 3 列的形式保存在单元格中。

import openpyxl
 
## opening the previously created xlsx file using 'load_workbook()' method
xlsx = openpyxl.load_workbook('appending.xlsx')
 
## getting the sheet to active
sheet = xlsx.active
 
## getting the reference of the cells which we want to get the data from
values = sheet['A1' : 'C4']
 
## printing the values of cells
for c1, c2, c3 in values:
print("{} {} {}".format(c1.value, c2.value, c3.value))
1 2 3
4 5 6
7 8 9
10 11 12

应用于单元格的切片方法返回一个 tuple,其中包含每行作为元组, 可以使用循环打印所有单元格的数据。

获取 .xlsx 工作表的尺寸

使用 dimensions方法也可以获得.xlsx板的尺寸,并且非常容易。

import openpyxl
 
## opening the previously created xlsx file using 'load_workbook()' method
xlsx = openpyxl.load_workbook('appending.xlsx')
 
## getting the sheet to active
sheet = xlsx.active
 
## getting the reference of the cells which we want to get the data from
dimensions = sheet.dimensions 
 
## printing the dimensions of the sheet
print(dimensions)
A1:C4

 

dimensions方法的输出是数据从某个单元格到某个单元格的工作表范围。

从 .xlsx 文件的行中获取数据

可以使用 rows方法从一个 Xlsx 文件的所有行中获取数据。

import openpyxl
 
## opening the previously created xlsx file using 'load_workbook()' method
xlsx = openpyxl.load_workbook('appending.xlsx')
 
## getting the sheet to active
sheet = xlsx.active
 
## getting the reference of the cells which we want to get the data from
rows = sheet.rows
 
## printing the values of cells using rows
for row in rows:
    for cell in row:
        print(cell.value, end = ' ')
 
    print("\n")
1 2 3 
4 5 6 
7 8 9 
10 11 12

rows 方法返回 generator, 其中包含工作表的所有行。

从 .xlsx 文件的列中获取数据

使用 columns 方法从 Xlsx 文件的所有列中获取数据。

import openpyxl
 
## opening the previously created xlsx file using 'load_workbook()' method
xlsx = openpyxl.load_workbook('appending.xlsx')
 
## getting the sheet to active
sheet = xlsx.active
 
## getting the reference of the cells which we want to get the data from
columns = sheet.columns
 
## printing the values of cells using rows
for column in columns:
    for cell in column:
        print(cell.value, end = ' ')
    print("\n")
1 4 7 10 
2 5 8 11 
3 6 9 12

使用 Excel 表格

1. 更改Excel工作表的名称

使用 title 变量更改给定 Excel 工作表的名称。示例:

import openpyxl
 
## initializing the xlsx
xlsx = openpyxl.Workbook()
 
## creating an active sheet to enter data
sheet = xlsx.active
 
## entering data into the A1 and B1 cells in the sheet
sheet['A1'] = 'Studytonight'
sheet['B1'] = 'A Programming Site'
 
## setting the title for the sheet
sheet.title = "Sample"
 
## saving the xlsx file using 'save' method
xlsx.save('sample.xlsx')

 

 2. 获取Excel工作表名称

使用 Openpyxl 模块获取 Xlsx 文件中存在的所有工作表的名称非常容易。 我们可以使用名为 get_sheet_names() 的方法来获取 Excel 文件中所有工作表的名称。

import openpyxl
 
## initializing the xlsx
xlsx = openpyxl.load_workbook('sample.xlsx')
 
## getting all sheet names
names = xlsx.get_sheet_names()
 
print(names)

上述程序的输出:

['Sample']

3. 在 Excel 文件中创建多个工作表

在创建第一个 Xlsx 文件时,只创建了一个工作表。 那么如何创建多个工作表并为其命名,如下所示:

import openpyxl
 
## initializing the xlsx
xlsx = openpyxl.Workbook()
 
## creating sheets
xlsx.create_sheet("School")
xlsx.create_sheet("College")
xlsx.create_sheet("University")
 
## saving the xlsx file using 'save' method
xlsx.save('multiple_sheets.xlsx')

 

 如上所述,使用在程序中提供的 3 个具有不同名称的新工作表创建了一个新的 Excel 文件。

4. 将数据添加到多个工作表

也可以轻松地将数据输入到Xlsx文件中的不同工作表中。在下面的程序中,我们将按其名称单独或一次性获取所有工作表,如上所述。接下来看一下如何使用工作表的名称获取工作表并在其中输入数据。

我们将使用先前创建的名为multiple_sheets.xlsx的Xlsx文件将数据输入工作表。

import openpyxl
 
## initializing the xlsx
xlsx = openpyxl.Workbook()
 
## creating sheets
xlsx.create_sheet("School")
xlsx.create_sheet("College")
xlsx.create_sheet("University")
 
## getting sheet by it's name
school = xlsx.get_sheet_by_name("School")
school['A1'] = 1
## getting sheet by it's name
college = xlsx.get_sheet_by_name("College")
college['A1'] = 2
 
## getting sheet by it's name
university = xlsx.get_sheet_by_name("University")
university['A1'] = 3
## saving the xlsx file using 'save' method
xlsx.save('multiple_sheets.xlsx')

更多了解openxl可以使用dir()方法。 

 我们无法使用 Openpyxl 模块修改现有的 Xlsx 文件,但可以从中读取数据。

 

转载自:https://blog.csdn.net/weixin_44906759/article/details/128048450

标签:xlsx,sheet,openpyxl,python,##,模块,active,openxl,data
From: https://www.cnblogs.com/shaoyishi/p/17219665.html

相关文章

  • python数据库学习笔记
    1.数据库管理软件的本质?本质就是C/S架构的套接字程序服务器套接字操作系统:linux计算机(本地文件)2.为什么要用数据库管理软件?可以自己写,要结合套接字程序,解决并发......
  • Python如何去掉字符串所有空格?
    Python去掉字符串所有空格的方法大致有五种,本篇文章通过代码实例为大家详细的介绍一下这五种方法,对学习Python的小伙伴非常具有参考价值,快跟着小编来学习一下吧。1......
  • JAVA开发 电信支付系统短信模块精准发送短信
    电信支付测试环境检测支付系统设备磁盘运行情况,监控磁盘到一定阀值,从client连到支付系统的统一短信模块,统一短信模块连接到短信发送系统,发送短信。短信模块也可应用于业务预......
  • Python多线程的坑——切换工作目录导致错误
    Python多线程的坑——切换工作目录导致错误复现:importosimporttimefromconcurrent.futuresimportThreadPoolExecutordefthread_func(a):origin=os.get......
  • python celery异步发送短信
    前言 Celery易于使用和维护,并且它 不需要配置文件 。 Celery有一个活跃、友好的社区来让你寻求帮助,包括一个 邮件列表 和一个 IRC频道 。倘若连接丢失或失......
  • 爬虫介绍、requests模块发送get请求、get请求携带参数、携带请求头、携带cookie、发送
    目录今日内容1爬虫介绍2requests模块发送get请求3get请求携带参数4携带请求头5携带cookie6发送post请求7响应Response8获取二进制数据9解析json#期终架构 -后......
  • 大爽Python入门教程 7-8 实践演示* 控制台版本——简易回合战斗
    大爽Python入门公开课教案点击查看教程总目录1背景介绍不知道大家有没有玩过魔塔。在我小时候,这是一个很经典又好玩的小游戏。其实最早想做一个控制台版本的简易魔......
  • 大爽Python入门教程 7-7 异常处理 try ... except Exception
    大爽Python入门公开课教案点击查看教程总目录1什么是异常Exception简单来讲,错误Error就是异常Exception。具体的,我们先来看几个错误。>>>2:3SyntaxError:illega......
  • Python让selenium代码执行完毕不关闭浏览器的方法
    pythonselenium在默认情况下,执行完业务逻辑的时候,浏览器也会进行自动关闭,如何让浏览器能够不退呢?下面给出一种我认为比较简单的解决方案供大家进行参考。用ChromeOption......
  • python文件操作
    一、文件编码 编码技术:翻译的规则,记录了如何将内容翻译成二进制,以及如何将二进制翻译回可识别内容;   计算机中有许多可用编码:UTF-8、GBK、Big5等; UTF-8是目前......