import pandas as pd
# 文件路径
filePath = r'C:\Users\Administrator\Desktop\Temp\1.xlsx'
# 1.读取 excel(默认第 1 行为标题,行索引为 0,即:header=0)
student = pd.read_excel(filePath)
print(student.columns)
# Index(['ID', 'Name', 'Age', 'Grade'], dtype='object')
场景2:指定第 n 行为标题
import pandas as pd
# 文件路径
filePath = r'C:\Users\Administrator\Desktop\Temp\1.xlsx'
# 场景2:excel 中第 2 行才是我们想要的标题(即:header=1)
student = pd.read_excel(filePath, header=1)
print(student.columns)
# Index(['ID', 'Name', 'Age', 'Grade'], dtype='object')
场景3:没有标题,需要人为给定
import pandas as pd
# 文件路径
filePath = r'C:\Users\Administrator\Desktop\Temp\1.xlsx'
# 场景3:excel 中没有标题,需要人为设定
student = pd.read_excel(filePath, header=None)
student.columns = ['ID', 'Name', 'Age', 'Grade']
student.set_index('ID', inplace=True) # 指定索引列,并替换原数据
student.to_excel(filePath) # 写入至 Excel
print(student)
# Name Age Grade
# ID
# 1 张三 18 90
# 2 李四 20 70
# 3 王五 2