使用Python处理xlsx表格的操作示例

  1. 载入表格文件
1
2
3
4
import openpyxl

workbook = openpyxl.load_workbook(r".\dataset.xlsx")
worksheet = workbook.worksheets[0]
  1. 获取行数和列数
1
2
raw_num = worksheet.max_row
col_num = worksheet.max_column
  1. 获取单元格内容
1
2
x = worksheet.cell(i, j).value
# i, j start with index 1
  1. 改变单元格内容
1
2
worksheet.cell(i, j, y)
# change the value to y
  1. 保存修改的内容
1
2
workbook.save(r".\dataset.xlsx")
# or workbook.save(r".\new_dataset.xlsx")