Python使用openpyxl模块处理Excel文件

作者:springsnow 时间:2021-10-03 06:45:10 

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

注释: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)

来源:https://www.cnblogs.com/springsnow/p/12566876.html

标签:Python,openpyxl,模块,处理,Excel,文件
0
投稿

猜你喜欢

  • 一篇jQuery小教程

    2007-10-15 12:49:00
  • asp 过滤尖括号内所有内容的正则代码

    2011-04-03 10:40:00
  • FF下,用 col 隐藏表格列的方法详解!

    2008-04-02 11:35:00
  • MySQL与MSSQl使用While语句循环生成测试数据的代码

    2024-01-22 01:42:47
  • Vue iframe更改src后页面未刷新问题解决方法

    2024-05-09 15:14:15
  • python中前缀运算符 *和 **的用法示例详解

    2022-05-19 08:41:31
  • asp网站生成静态页面攻略

    2007-11-04 15:09:00
  • javascript实现获取图片大小及图片等比缩放的方法

    2024-04-16 10:29:33
  • Python实现发送邮件到自己邮箱

    2023-10-18 17:08:11
  • matplotlib.pyplot绘图显示控制方法

    2023-07-03 15:44:20
  • 你是真正的用户体验设计者吗? Ⅲ

    2008-03-27 09:04:00
  • 最新Adobe 2022全新上线 Adobe 2022永久免费使用教程

    2022-02-01 14:59:07
  • python中NumPy的安装与基本操作

    2023-08-27 03:03:53
  • Ubuntu20.04环境安装tensorflow2的方法步骤

    2023-07-04 06:41:21
  • Python 判断文件或目录是否存在的实例代码

    2021-08-16 14:44:49
  • Python画图常用命令大全(详解)

    2023-04-17 15:20:16
  • PHP仿微信多图片预览上传实例代码

    2024-05-03 15:27:45
  • python中copy()与deepcopy()的区别小结

    2022-02-22 19:39:14
  • 基于Python实现一个简单的银行转账操作

    2023-05-29 16:39:26
  • Golang中的panic之避免和处理程序中的异常情况

    2024-02-20 10:22:49
  • asp之家 网络编程 m.aspxhome.com