使用xlrd库在Python中对Excel文件进行读取和写入操作
发布时间:2024-01-18 08:20:53
在Python中,可以使用xlrd库对Excel文件进行读取操作。该库能够读取Excel文件中的内容,并将其转化为Python中的数据结构。
首先,需要确保已经安装了xlrd库。可以使用以下命令进行安装:
pip install xlrd
下面是一个使用xlrd库读取Excel文件的例子:
import xlrd
# 打开Excel文件
workbook = xlrd.open_workbook('example.xlsx')
# 获取所有的sheet名称
sheet_names = workbook.sheet_names()
print("Sheet Names: ", sheet_names)
# 选择 个sheet
sheet = workbook.sheet_by_index(0)
# 获取sheet的行数和列数
num_rows = sheet.nrows
num_cols = sheet.ncols
print("Number of Rows: ", num_rows)
print("Number of Columns: ", num_cols)
# 遍历每一行,并打印每一列的值
for row_idx in range(num_rows):
row_data = []
for col_idx in range(num_cols):
cell_value = sheet.cell_value(row_idx, col_idx)
row_data.append(cell_value)
print("Row {}: {}".format(row_idx, row_data))
在上述例子中,首先使用open_workbook()函数打开Excel文件,并获取所有的sheet名称。然后选择 个sheet,并通过nrows和ncols属性获取行数和列数。最后,通过遍历每一行和每一列,打印出每个单元格的值。
除了读取Excel文件,也可以使用xlrd库进行写操作。下面是一个使用xlrd库写入Excel文件的例子:
import xlrd
from xlutils.copy import copy
# 打开Excel文件
workbook_rd = xlrd.open_workbook('example.xlsx')
# 创建一个可写的副本
workbook_wt = copy(workbook_rd)
# 选择 个sheet
sheet_wt = workbook_wt.get_sheet(0)
# 写入新的数据
sheet_wt.write(0, 3, 'New Data')
# 保存更改后的Excel文件
workbook_wt.save('example_modified.xlsx')
在上述例子中,首先使用open_workbook()函数打开Excel文件,并使用copy()函数创建一个可以进行写操作的副本。然后通过get_sheet()方法选择 个sheet,并使用write()方法在指定的单元格写入新的数据。最后,使用save()方法保存更改后的Excel文件。
总结来说,通过使用xlrd库可以方便地读取和写入Excel文件。通过掌握xlrd库的使用,可以在Python中对Excel文件进行灵活的操作。
