广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python使用openpyxl模块处理Excel文件
  • 437
分享到

Python使用openpyxl模块处理Excel文件

2024-04-02 19:04:59 437人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

首先贴出四种方法适用范围比较: 注释:excel 2003 即XLS文件有大小限制即65536行256列,所以不支持大文件。而Excel 2007以上即XLSX文件的限制则为1048

首先贴出四种方法适用范围比较:

注释:excel 2003 即XLS文件有大小限制即65536行256列,所以不支持大文件。而Excel 2007以上即XLSX文件的限制则为1048576行16384列

一、xlutils & xlrd & xlwt

最原始的莫过于两位老牌黄金搭档xlrd xlwt了,针对二者的封装有如下模块:

  • xlutils:https://pypi.org/project/xlutils/
  • xlrd:Https://pypi.org/project/xlrd/
  • xlwt:https://pypi.org/project/xlwt/

为什么把这三个一起说?

首先,xlutils封装了xlrd xlwt,所以在使用前,会先下载这两个依赖的模块。

其次,这两个模块主要用于处理xls文件,而对xlsx的文件处理很挫,甚至xlwt不支持…

但为何到现在依然在使用这些模块,因为他对xls文档处理的优势….

1、xlutils

官方文档:https://xlutils.readthedocs.io/en/latest/api.html

GitHub项目:https://github.com/python-excel/xlutils

安装:(如果没安装xlrd、xlwt,会自动安装这2个模块)

pip install xlutils

使用:

import xlrd
import xlwt
import xlutils

import xlutils.copy as copy

rdbook = xlrd.open_workbook('first.xls')
wtbook = copy.copy(rdbook)
wtsheet = wtbook.get_sheet(0)
type(wtsheet)
wtsheet.write(0,0,'pcat.cc')
wtbook.save('second.xls')

2、xlrd

xlrd is a library for reading data and fORMatting information from Excel files, whether they are .xls or .xlsx files.

官方文档:https://xlrd.readthedocs.io/en/latest/api.html

github项目:https://github.com/Python-excel/xlrd

安装:pip install xlrd

使用:只能读.xls、.xlsx文件(xlrd0.8.0+版本支持读取xlsx文件)

import xlrd
book = xlrd.open_workbook("pcat.xls")
print("The number of worksheets is {0}".format(book.nsheets))
print("Worksheet name(s): {0}".format(book.sheet_names()))
sh = book.sheet_by_index(0)
print("{0} {1} {2}".format(sh.name, sh.nrows, sh.ncols))
print("Cell B3 is {0}".format(sh.cell_value(rowx=2, colx=1)))
for rx in range(sh.nrows):
    print(sh.row(rx))

3、xlwt

xlwt is a library for writing data and formatting information to older Excel files (ie: .xls)

官方文档:https://xlwt.readthedocs.io/en/latest/api.html

github项目:https://github.com/python-excel/xlwt

安装:pip install xlwt

使用:用xlwt创建一个简单的.xls文件

import xlwt
from datetime import datetime

style0 = xlwt.easyxf('font: name Times New Roman, color-index red, bold on',
    num_format_str='#,##0.00')
style1 = xlwt.easyxf(num_format_str='YYYY-MM-DD HH:MM:SS')

wb = xlwt.Workbook()
ws = wb.add_sheet('A Test Sheet')

ws.write(0, 0, 1234.56, style0)
ws.write(1, 0, datetime.now(), style1)
ws.write(2, 0, 1)
ws.write(2, 1, 1)
ws.write(2, 2, xlwt.Formula("A3+B3"))

wb.save('example.xls')

二、pandas(推荐)

pandas

https://www.pypandas.cn/

pandas作为数据分析利器,在读写excel方面,依赖库xlrd和xlwt。

import   pandas   as pd
 
#方法一:默认读取第一个表单
df=pd.read_excel('lemon.xlsx')#这个会直接默认读取到这个Excel的第一个表单
data=df.head()#默认读取前5行的数据
print("获取到所有的值:\n{0}".format(data))#格式化输出
 
#方法二:通过指定表单名的方式来读取
df=pd.read_excel('lemon.xlsx',sheet_name='student')#可以通过sheet_name来指定读取的表单
data=df.head()#默认读取前5行的数据
print("获取到所有的值:\n{0}".format(data))#格式化输出
 
#方法三:通过表单索引来指定要访问的表单,0表示第一个表单
#也可以采用表单名和索引的双重方式来定位表单
#也可以同时定位多个表单,方式都罗列如下所示
df=pd.read_excel('lemon.xlsx',sheet_name=['python','student'])#可以通过表单名同时指定多个
# df=pd.read_excel('lemon.xlsx',sheet_name=0)#可以通过表单索引来指定读取的表单
# df=pd.read_excel('lemon.xlsx',sheet_name=['python',1])#可以混合的方式来指定
# df=pd.read_excel('lemon.xlsx',sheet_name=[1,2])#可以通过索引 同时指定多个
data=df.values#获取所有的数据,注意这里不能用head()方法哦~
print("获取到所有的值:\n{0}".format(data))#格式化输出

三、xlsxwriter

https://xlsxwriter.readthedocs.io/

xlsxwriter拥有丰富的特性,支持图片/表格/图表/筛选/格式/公式等,功能与openpyxl相似,优点是相比 openpyxl 还支持 VBA 文件导入,迷你图等功能,缺点是不能打开/修改已有文件,意味着使用 xlsxwriter 需要从零开始。

注意:XlsxWriter不支持.xls格式。

代码示例:

import xlsxwriter
 
# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('Expenses01.xlsx')
worksheet = workbook.add_worksheet()
 
# Some data we want to write to the worksheet.
expenses = (['Rent', 1000], ['Gas',     100],['Food',   300], ['Gym',       50],)
 
# Start from the first cell. Rows and columns are zero indexed.
row = 0
col = 0
 
# Iterate over the data and write it out row by row.
for item, cost in (expenses):       
   worksheet.write(row, col,     item)       
   worksheet.write(row, col + 1, cost)       
   row += 1
 
# Write a total using a formula.
worksheet.write(row, 0, 'Total')
worksheet.write(row, 1, '=SUM(B1:B4)')
worksheet.write('A1', 'Hello world')

workbook.close()

四、openpyxl(推荐)

读写 Excel 2010 xlsx/xlsm files.

最后要说说个人比较常用,也很方便的一个excel处理模块openpyxl….这个模块突出的优势在于,对excel单元格样式的设置方面特别详细。

注意:openpyxl不支持.xls格式。读写文件前记得多备注,有时候可能有bug。

官方文档:https://openpyxl.readthedocs.io/en/stable/

安装:pip install openpyxl

1、写一个工作簿

from openpyxl import Workbook
from openpyxl.utils import get_column_letter

wb = Workbook()
dest_filename = 'empty_book.xlsx'

ws1 = wb.active
ws1.title = "range names"

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

ws2 = wb.create_sheet(title="Pi")
ws2['F5'] = 3.14
ws2['A1'] = 42  # Data can be assigned directly to cells
ws2.append([1, 2, 3])# Rows can also be appended

# Python types will automatically be converted
import datetime
ws2['A2'] = datetime.datetime.now()

ws3 = wb.create_sheet(title="Data")
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)))
print(ws3['AA10'].value)

wb.save(filename = dest_filename)

2、读取现有工作簿

from openpyxl import load_workbook

wb = load_workbook(filename = 'empty_book.xlsx')
sheet_ranges = wb['Sheet1']
print(sheet_ranges['D18'].value)

3.、插入图像 (需要依赖pillow..)

from openpyxl import Workbook
from openpyxl.drawing.image import Image
 
wb = Workbook()
ws = wb.active
ws['A1'] = 'You should see three loGos below'
img = Image('logo.png') # create an image
ws.add_image(img, 'A1') # add to worksheet and anchor next to cells
wb.save('logo.xlsx')

4、使用样式

样式用于在屏幕上显示时更改数据的外观。它们还用于确定数字的格式。

样式可以应用于以下方面:

  • 字体设置字体大小,颜色,下划线等
  • 填充以设置图案或颜色渐变
  • 边框设置单元格上的边框
  • 单元格排列
  • 保护

以下是默认值:

from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font

font = Font(name='Calibri',size=11,bold=False, italic=False,vertAlign=None,underline='none',strike=False, color='FF000000')
fill = PatternFill(fill_type=None, start_color='FFFFFFFF', end_color='FF000000')
border = Border(left=Side(border_style=None,color='FF000000'),   right=Side(border_style=None,color='FF000000'), 
     top=Side(border_style=None, color='FF000000'), bottom=Side(border_style=None, color='FF000000'), 
                 diagonal=Side(border_style=None, color='FF000000'), diagonal_direction=0,   outline=Side(border_style=None,color='FF000000'), 
                 vertical=Side(border_style=None,color='FF000000'),   horizontal=Side(border_style=None,color='FF000000') )
alignment=Alignment(horizontal='general',vertical='bottom',   text_rotation=0, wrap_text=False,   shrink_to_fit=False, indent=0)
number_format = 'General'
protection = Protection(locked=True,   hidden=False)

到此这篇关于Python使用openpyxl模块处理Excel文件的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持编程网。

--结束END--

本文标题: Python使用openpyxl模块处理Excel文件

本文链接: https://www.lsjlt.com/news/118535.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python使用openpyxl模块处理Excel文件
    首先贴出四种方法适用范围比较: 注释:Excel 2003 即XLS文件有大小限制即65536行256列,所以不支持大文件。而Excel 2007以上即XLSX文件的限制则为1048...
    99+
    2022-11-11
  • Python如何使用openpyxl模块处理Excel文件
    这篇文章主要介绍“Python如何使用openpyxl模块处理Excel文件”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Python如何使用openpyxl模块处理Excel文件”文章能帮助大家解...
    99+
    2023-06-30
  • Python使用openpyxl处理Excel文件详情
    目录前言1. Excel窗口2. 读取Excel文件3. 写入Excel文件4. 复制Excel文件5. 创建工作表6. 设置单元格字体及颜色7. 数学公式的使用8. 设置单元格宽高...
    99+
    2022-11-11
  • python处理excel文件之xlsxwriter 模块
    目录模块基本使用写入更多样式数据其余样式扩展xlsxwriter 中的 write 方法xlsxwriter 关闭文件其它需要了解的方法xlsxwriter 模块的优缺点优点缺点模块...
    99+
    2022-11-11
  • Python怎么用openpyxl模块操作Excel
    这篇文章主要介绍了Python怎么用openpyxl模块操作Excel的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Python怎么用openpyxl模块操作Excel文章都会有所收获,下面我们一起来看看吧。正...
    99+
    2023-06-30
  • Python使用openpyxl读写excel文件
    需求:读入sample.xlsx中的信息,通过分析其中的身份证号信息,得到每个人的出生日期,性别,年龄,所在省份,星座,属相等等,将结果写入到另一个excel文件中。 首先,要使用openpyxl第三方库需要安装,安装方法如下: pip i...
    99+
    2023-09-11
    python
  • python怎么用xlsxwriter模块处理excel文件
    本篇内容介绍了“python怎么用xlsxwriter模块处理excel文件”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!模块安装:pip&...
    99+
    2023-06-30
  • python 使用 openpyxl 处理 Excel 教程
    目录 前言一、安装openpyxl库二、新建excel及写入单元格1.创建一个xlsx格式的excel文件并保存2.保存成流(stream)3.写入单元格 三、创建sheet工作表及操作四...
    99+
    2023-09-05
    excel python 开发语言 openpyxl
  • 使用Python读取和修改Excel文件(基于xlrd、xlwt和openpyxl模块)
    目录1、使用xlrd模块对xls文件进行读操作1.1 获取工作簿对象1.2 获取工作表对象1.3 获取工作表的基本信息1.4 按行或列方式获得工作表的数据2、使用xlwt模块对xls...
    99+
    2022-11-12
  • Python 操作Excel-openpyxl模块用法实例
    目录openpyxl 的用法实例1.1 Openpyxl 库的安装使用1.2 Excel 的新建、读取、保存1.2.1 新建保存工作簿(覆盖创建)1.2.2 读取保存工作簿1.2.3...
    99+
    2023-05-19
    Python Excel-openpyxl模块使用 Excel-openpyxl用法
  • Python中怎么使用openpyxl模块
    这篇文章主要介绍“Python中怎么使用openpyxl模块”,在日常操作中,相信很多人在Python中怎么使用openpyxl模块问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Python中怎么使用open...
    99+
    2023-06-27
  • Python文件处理、os模块、glob模块
    目录一、文件基本的操作1、open() 打开文件2、read() 读文件3、write()写文件:4、with open()方法二、文件的打开模式1、文件r打开模式1、读文本2、读字...
    99+
    2022-11-11
  • 如何在Python中使用openpyxl模块
    这篇文章主要介绍了如何在Python中使用openpyxl模块,此处给大家介绍的非常详细,对大家的学习或工作具有一定的参考价值,需要的朋友可以参考下:Python主要用来做什么Python主要应用于:1、Web开发;2、数据科学研究;3、网...
    99+
    2023-06-06
  • 用Python处理Excel文件
    四种python处理excel模块PK我主要尝试了四种工具,在此并不会给出他们的排名,因为在不同的应用场景下,做出的选择会不同。 XlsxWriterxlrd&xlwtOpenPyXLMicrosoft Excel API介绍可以创...
    99+
    2023-01-31
    文件 Python Excel
  • python操作excel之openpyxl模块读写xlsx格式使用方法详解
    openpyxl模块支持.xls和.xlsx格式的excel创建,但是只支持.xlsx格式的读取操作,不支持.xls的读取(可以使用xlrd模块来读取,写入操作也可使用xlwt模块)...
    99+
    2022-12-21
    python使用openpyxl模块读写xlsx格式 openpyxl创建新的excel openpyxl获取默认工作表 openpyxl删除工作表 openpyxl单元格操作
  • python处理excel文件
    python操作excel主要用到xlrd和xlwt这两个库,即xlrd是读excel,xlwt是写excel的库。可从这里下载https://pypi.python.org/pypi。下面分别记录python读和写excel.python...
    99+
    2023-01-31
    文件 python excel
  • python 处理excel文件
    有两种办法1.使用 Xlrd/xlwt 操作 Excelhttp://liluo.org/blog/2011/01/python-using-xlrd-xlwt-operate-excel/ Xlrd/xlwt库的功能有限,比如有的exce...
    99+
    2023-01-31
    文件 python excel
  • Python文件处理方法、os模块和glob模块如何使用
    这篇文章主要讲解了“Python文件处理方法、os模块和glob模块如何使用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Python文件处理方法、os模块和glob模块如何使用”吧!一、文...
    99+
    2023-07-06
  • Python文件处理方法、os模块和glob模块怎么使用
    这篇“Python文件处理方法、os模块和glob模块怎么使用”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Python文件...
    99+
    2023-06-30
  • Python文件路径处理模块pathlib怎么使用
    这篇文章主要介绍了Python文件路径处理模块pathlib怎么使用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Python文件路径处理模块pathlib怎么使用文章都会有所收获,下面我们一起来看看吧。1. ...
    99+
    2023-07-05
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作