zoukankan      html  css  js  c++  java
  • Python操作Excel文件

    Excel读取:

    # 导入模块
    import xlrd #这个模块不是python,需要下载安装,直接按快捷键Alt+Shift+Enter,PyCharm会自动安装
    # 读取到excel文件
    data = xlrd.open_workbook("xxx.xlsx")
    # 获取列表
    table = data.sheet_by_index(0)
    # 获取所有的行数
    nrows = table.nrows
    # # 获取所有的列数
    # ncols = table.ncols
    
    # 获取第一行的数据
    first_row_name_list = table.row_values(0)
    print(first_row_name_list)
    
    # 定义一个列表保存所有行的数据
    info_list = []
    # 遍历所有行
    for rownum in range(1, nrows):
        # 获取
        row = table.row_values(rownum)
        # 如果row有数据
        if row:
            info_list.append(row)
    
    print(info_list)

    Excel写入:

    # 导入模块
    import xlsxwriter #这个模块不是python,需要下载安装,直接按快捷键Alt+Shift+Enter,PyCharm会自动安装
    # 打开student.xlsx文件
    workbook = xlsxwriter.Workbook("student.xlsx")
    # 创建一张工作表
    worksheet = workbook.add_worksheet()
    # 设置第一行信息
    worksheet.write(0, 0, "学号")
    worksheet.write(0, 1, "姓名")
    worksheet.write(0, 2, "年龄")
    
    # 学生信息列表
    student_list = [{"name": "小A", "age": 20, "no": "no1"},
                    {"name": "小B", "age": 21, "no": "no2"},
                    {"name": "小C", "age": 20, "no": "no3"},
                    {"name": "小D", "age": 23, "no": "no4"},
                    {"name": "小E", "age": 25, "no": "no5"}]
    
    # 遍历列表
    for i, info in enumerate(student_list):
        # 写入数据
        # write(第x行, 第x列, 写入的数据)
        worksheet.write(i + 1, 0, info["no"])
        worksheet.write(i + 1, 1, info["name"])
        worksheet.write(i + 1, 2, info["age"])
    
    # 关闭文件
    workbook.close()
  • 相关阅读:
    Codeforces 1316B String Modification
    Codeforces 1305C Kuroni and Impossible Calculation
    Codeforces 1305B Kuroni and Simple Strings
    Codeforces 1321D Navigation System
    Codeforces 1321C Remove Adjacent
    Codeforces 1321B Journey Planning
    Operating systems Chapter 6
    Operating systems Chapter 5
    Abandoned country HDU
    Computer HDU
  • 原文地址:https://www.cnblogs.com/LJP-JumpAndFly/p/14751343.html
Copyright © 2011-2022 走看看