python爬虫之数据存储(二):Excel文件处理

Excel文件处理:

Sheet相关的操作:

workbook = xlrd.open_workbook("成绩表.xlsx")

# 获取所有的sheet名字
# print(workbook.sheet_names())

# 根据索引获取指定的sheet对象
# sheet = workbook.sheet_by_index(1)
# print(sheet.name)

# 根据名称获取指定的sheet对象
# sheet = workbook.sheet_by_name("2班")
# print(sheet.name)

# 获取所有的sheet对象
# sheets = workbook.sheets()
# for sheet in sheets:
#     print(sheet.name)

# 获取指定sheet的行数和列数
sheet = workbook.sheet_by_index(0)
print({
    
    "rows":sheet.nrows,"cols":sheet.ncols})

Cell相关的操作:

from xlrd.sheet import Cell
sheet = workbook.sheet_by_index(0)
cell = sheet.cell(1,1)
print(cell.value)

# cells = sheet.row_slice(1,1,4)
# for cell in cells:
#     print(cell.value)

# cells = sheet.col_slice(0,1,sheet.nrows)
# for cell in cells:
#     print(cell.value)

# cell_value = sheet.cell_value(0,1)
# print(cell_value)

# cell_values = sheet.col_values(1,1,sheet.nrows)
# print(cell_values)

# cell_values = sheet.row_values(1,1,sheet.ncols)
# print(cell_values)

Cell中常用的数据类型:

sheet = workbook.sheet_by_index(0)
# cell = sheet.cell(0,0)
# print(cell.ctype)
# print(xlrd.XL_CELL_TEXT)

# cell = sheet.cell(1,1)
# print(cell.ctype)
# print(xlrd.XL_CELL_NUMBER)

# cell = sheet.cell(19,0)
# print(cell.ctype)
# print(xlrd.XL_CELL_DATE)

# cell = sheet.cell(19,0)
# print(cell.ctype)
# print(xlrd.XL_CELL_BOOLEAN)


cell = sheet.cell(1,1)
print(cell.ctype)
print(xlrd.XL_CELL_EMPTY)

写入Excel文件:

  1. 导入xlwt模块。
  2. 创建一个Workbook对象。
  3. 创建一个Sheet对象。
  4. 使用sheet.write方法把数据写入到Sheet下指定行和列中。如果想要在原来workbook对象上添加新的cell,那么需要调用put_cell来添加。
  5. 保存成Excel文件。

编辑Excel文件:

  1. 先读取原来的Excel文件。
  2. 然后在读取的sheet上面进行cell的修改,可以使用sheet.put_cell(row,col,ctype,value,None)方法实现。
  3. 再重新创建一个新的excel文件,然后把之前读取到的数据写入到新的excel文件中。

猜你喜欢

转载自blog.csdn.net/zdfsb/article/details/108528653