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')