• Python用xlrd读取Excel数据到list中再用xlwt把数据写入到新的Excel中


    一、先用xlrd读取Excel数据到list列表中(存入列表中的数据如下图所示)

    import xlrd as xd #导入需要的包
    import xlwt
    data =xd.open_workbook (r'C:python测试文件我的三国啊.xlsx') #打开excel表所在路径
    sheet = data.sheet_by_name('Sheet1')  #读取数据,以excel表名来打开
    #print(sheet.nrows)
    #print(sheet.cell_value)
    d = [] #新建一个列表
    for r in range(sheet.nrows): #将表中数据按行逐步添加到列表中,最后转换为list结构
        data1 = []
        for c in range(sheet.ncols):
            data1.append(sheet.cell_value(r,c))
        d.append(list(data1))
    
    print(d)

     二、再用xlwt把列表中的数据写入到新的Excel文件中

    workbook=xlwt.Workbook()
    sheet1=workbook.add_sheet('sheet1',cell_overwrite_ok=True)
    row=0
    for colours in d:
        for i in range(0, len(colours)):
          #print(i, colours[i])
          sheet1.write(row,i,colours[i])
        row=row+1
        #print(row)
    
    workbook.save('test.xlsx')

    三、完整代码展示

    import xlrd as xd #导入需要的包
    import xlwt
    data =xd.open_workbook (r'C:python测试文件我的三国啊.xlsx') #打开excel表所在路径
    sheet = data.sheet_by_name('Sheet1')  #读取数据,以excel表名来打开
    #print(sheet.nrows)
    #print(sheet.cell_value)
    d = [] #新建一个列表
    for r in range(sheet.nrows): #将表中数据按行逐步添加到列表中,最后转换为list结构
        data1 = []
        for c in range(sheet.ncols):
            data1.append(sheet.cell_value(r,c))
        d.append(list(data1))
    
    print(d)
    
    workbook=xlwt.Workbook()
    sheet1=workbook.add_sheet('sheet1',cell_overwrite_ok=True)
    row=0
    for colours in d:
        for i in range(0, len(colours)):
          #print(i, colours[i])
          sheet1.write(row,i,colours[i])
        row=row+1
        #print(row)
    
    workbook.save('test.xlsx')
  • 相关阅读:
    模块-和包
    re模块
    递归函数
    内置函数
    C++ 创建文件的方法
    C++多态的实现条件
    C++常见错误总结
    Http客户端跳转和服务器端跳转的区别
    struts1学习
    Java 核心读书笔记 第11章
  • 原文地址:https://www.cnblogs.com/lcl-cn/p/15327353.html
Copyright © 2020-2023  润新知