用pandas新建excel并设置表头

 代码如下:

import pandas

#创建一个名字为excel_file_name的excel文件
#这里把表头设置为(姓名name,年龄age,性别gender,城市city,技能skill)   
def create_form(excel_file_name):
    form_header = ['姓名name', '年龄age', '性别gender', '城市city', '技能skill']
    df = pandas.DataFrame(columns=form_header)
    df.to_excel(excel_file_name, index=False) 

    
#这里把信息插入到excel里面    
def add_info_to_form(excel_file_name, name, age, gender, city, skill):
    df = pandas.read_excel(excel_file_name)
    row_index = len(df) + 1  #当前excel内容有几行
    df.loc[row_index] = [name, age, gender, city, skill]
    df.to_excel(excel_file_name, index=False)


if __name__ == "__main__":
    excel_file_name = 'test.xls'
    create_form(excel_file_name)
    add_info_to_form(excel_file_name, '张瑞', 27, '女', '杭州', '吃')
    add_info_to_form(excel_file_name, '张瑞', 27, '女', '杭州', '吃')

运行结果:

已标记关键词 清除标记
相关推荐