一 xlrd、xlwt 和 xlutils 包的介绍
OpenPyXL 和 xlrd、xlwt 、xlutils 的区别在笔记 15 。
二 如何使用 xlrd 读取文件
1.获取所有工作表的名称
book.sheet_names():得到一个列表。
python
import xlrd
import xlwt
from xlwt.Utils import cell_to_rowcol2
import xlutils
import excel
book = xlrd.open_workbook("xl/stores.xls")
print(book.sheet_names())
for sheet in book.sheets():
print(sheet.name)
2.获取工作表对象
通过名称或者索引(从0开始)。
python
sheet = book.sheet_by_index(0)
sheet = book.sheet_by_name("2019")
3.获取工作表维度
python
print(sheet.nrows)
print(sheet.ncols)
补充:
xlrd
在处理 Excel 文件时,使用sheet.nrows
和sheet.ncols
属性来获取工作表的总行数和总列数,而这些值反映的是工作表的实际维度,而不是 "使用区域"(used range)的维度。在 Excel 中,"使用区域" 是指包含数据的矩形区域。它排除了不包含数据的空行和空列。
sheet.nrows
返回工作表中的总行数。
sheet.ncols
返回工作表中的总列数。这些值表示整个工作表的大小,包括可能存在的空行和空列。
如果你只关心包含数据的区域,而忽略空行和空列,你可能需要手动计算"使用区域"。这可以通过检查每行和每列是否有数据来实现。例如,遍历所有行和列,找到第一个和最后一个包含数据的行和列,以确定实际使用的区域。
4.使用A1表示法或者单元格索引(从0开始)读取各个单元格的值
python
sheet.cell(*cell_to_rowcol2("B3")).value
sheet.cell(2, 1).value
sheet.cell(*cell_to_rowcol2("B3")).value:
cell_to_rowcol2("B3"):
用于将 Excel 风格的单元格地址(如 "B3"
) 转换为行号和列号的元组 (row, col)
。"B3"
会被转换为 (2, 1)。
*cell_to_rowcol2("B3")
:*
是解包操作符,用于将元组 (2, 1)
解包为两个独立的参数 2
和 1
。
sheet.cell(2, 1).value:
获取指定单元格的值。.value
属性返回单元格中的内容。
sheet.cell(2, 1)
获取第 3 行(索引 2)第 2 列(索引 1)的单元格对象。
5.使用 excel 模块读取一个区间中单元格的值
python
data = excel.read(sheet, "B2")
data[:2] # 打印前两行
6.处理大型文件
在读取旧式的 xls 格式的大型文件时,xlrd 可以按需加载工作表。
python
with xlrd.open_workbook("xl/stores.xls", on_demand=True) as book:
sheet = book.sheet_by_index(0) # 只加载第一张工作表
with
语句用于确保文件在使用完毕后能够被正确关闭。book
变量代表打开的工作簿对象。
on_demand=True
参数指定了按需加载模式。在按需加载模式下,xlrd
不会一次性将整个工作簿加载到内存中,加载特定的工作表或单元格数据。
sheet = book.sheet_by_index(0)
:使用 sheet_by_index
方法从工作簿 book
中获取了索引为0的工作表,并将其赋值给变量sheet
。工作表的索引是从0开始的,所以sheet_by_index(0)
返回的是第一个工作表。
需要注意的是,由于使用了按需加载模式,此时只有第一个工作表的数据被加载到了内存中。
搭配 pandas 在上下文管理器模式下使用 xlrd:
python
with xlrd.open_workbook("xl/stores.xls", on_demand=True) as book:
with pd.ExcelFile(book, engine="xlrd") as f:
df = pd.read_excel(f, sheet_name=0)
7.关闭工作簿
调用 book.release_ resources() 。
三 如何使用 xlwt 写入文件
xlwt 并不能生成图表,并且只支持 bmp 格式的图片。
1.导包
python
import xlwt
from xlwt.Utils import cell_to_rowcol2
import datetime as dt
import excel
2.实例化工作簿
python
book = xlwt.Workbook()
3.添加工作表并为其命名
python
sheet = book.add_sheet("Sheet1")
4.使用A1表示法和单元格索引(从0开始)写入各个单元格
python
sheet.write(*cell_to_rowcol2("A1"), "Hello 1")
sheet.write(r=1, c=0, label="Hello 2")
在 xlwt
中,sheet.write()
方法用于向工作表的特定单元格写入数据。这个方法通常需要三个参数:行号 (r
)、列号 (c
)、以及要写入的数据 (label
)。
sheet.write(*cell_to_rowcol2("A1"), "Hello 1")
:这行代码的目的是将字符串 "Hello 1"
写入到单元格 A1
。这里使用了 cell_to_rowcol2()
函数,该函数接受一个 Excel 单元格地址(如 "A1"
),并返回一个包含行号和列号的元组。*cell_to_rowcol2("A1")
是解包操作,它将这个元组解包为两个独立的参数(行号和列号),然后传递给 sheet.write()
方法。
为什么有解包操作:
因为
sheet.write()
方法期望接收三个独立的参数:行号 (r
)、列号 (c
) 和要写入的数据 (label
)。然而cell_to_rowcol2()
函数返回的是一个包含两个元素的元组,这两个元素分别代表行号和列号。
pythondef return_tuple(): return (1, 2) # 不使用解包 a, b = return_tuple() # a = 1, b = 2 # 使用解包作为函数参数 def print_numbers(x, y): print(x, y) print_numbers(*return_tuple()) # 输出: 1 2
return_tuple
函数,该函数不接受任何参数,并返回一个包含两个整数(1, 2)
的元组。通过调用return_tuple()
函数,并将其返回值赋给两个变量a
和b
,其中a
被赋值为1
,b
被赋值为2
。
print_numbers
的函数,该函数接受两个参数x
和y
,并将它们打印出来。解包操作允许我们将一个元组中的元素作为参数列表传递给另一个函数,而无需手动提取元组中的每个元素。
sheet.write(r=1, c=0, label="Hello 2")
:这行代码直接将字符串 "Hello 2"
写入到第2行第1列的单元格中( r=1
表示第2行,c=0
表示第1列),label
参数指定了要写入的数据。
5.格式化:填充颜色、对齐、边框和字体
python
formatting = xlwt.easyxf("font: bold on, color red;"
"align: horiz center;"
"borders: top_color red, bottom_color red,"
"right_color red, left_color red,"
"left thin, right thin,"
"top thin, bottom thin;"
"pattern: pattern solid, fore_color yellow;")
sheet.write(r=2, c=0, label="Hello 3", style=formatting)
6.数字格式化(使用Excel的格式化字符串)
python
number_format = xlwt.easyxf(num_format_str="0.00")
sheet.write(3, 0, 3.3333, number_format)
7.日期格式化(使用Excel的格式化字符串)
python
date_format = xlwt.easyxf(num_format_str="mm/dd/yyyy")
sheet.write(4, 0, dt.datetime(2012, 2, 3), date_format)
8.使用公式
python
sheet.write(5, 0, xlwt.Formula("SUM(A4, 2)"))
9.二维列表(使用excel模块)
python
data = [[None, "North", "South"],
["Last Year", 2, 5],
["This Year", 3, 6]]
excel.write(sheet, data, "A10")
10.图片(只支持添加bmp格式的图片)
python
sheet.insert_bitmap("images/python.bmp", 0, 2)
11.将文件写入磁盘
python
book.save("xlwt.xls")
四 如何使用 xlutils 编辑文件
工作表通过 xlrd 读取包含格式在内的文件内容(将 formatting_info 的参数设置为 True),然后
再通过 xlwt 将其间做出的更改写入文件。
补充:formatting_info
参数
formatting_info
参数是一个可选参数,它用于指示在打开Excel文件时是否加载格式信息。当
formatting_info=True
时,xlrd
会尝试读取并加载Excel文件中的格式信息,如字体、颜色、边框、对齐方式等。这可能会增加内存消耗,因为需要存储更多的格式数据。当
formatting_info=False
时,xlrd
不会加载格式信息,只读取数据内容。这通常可以节省内存,并且对于只需要数据而不需要格式的应用场景来说足够了。
python
import xlutils.copy
book = xlrd.open_workbook("xl/stores.xls", formatting_info=True)
book = xlutils.copy.copy(book)
book.get_sheet(0).write(0, 0, "changed!")
book.save("stores_edited.xls")
book = xlutils.copy.copy(book)
:使用 xlutils.copy
模块的 copy
函数复制由 xlrd
打开的工作簿。这一步是必要的,因为xlrd
打开的工作簿是只读的,而 xlutils.copy
提供了一个可写的工作簿副本。
book.get_sheet(0).write(0, 0, "changed!")
:修改第一个工作表(索引为0)的第一个单元格(行0,列0)的内容为"changed!"。
book.save("stores_edited.xls")
:尝试保存修改后的工作簿到名为 stores_edited.xls
的文件。