python读写excel文件

2021/9/20 1:04:55

本文主要是介绍python读写excel文件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

import xlrd
import xlwt

#读取excel文件
# hcz = 火车站
hcz = xlrd.open_workbook('D:\\pythontest\\火车站表1.xls')# 打开Excel文件
sheet = hcz.sheet_by_name('产品1') #通过excel表格名称(rank)获取工作表
name = []  # 第一列
price = []  # 第二列
for a in range(sheet.nrows):  # 循环读取表格内容(每次读取一行数据)
    cells = sheet.row_values(a)  # 每行数据赋值给cells
    name_data = cells[0]  # 因为表内可能存在多列数据,0代表第一列数据,1代表第二列,以此类推
    name.append(name_data)  # 存储第一列所有数据
    price_data = cells[1]  # 因为表内可能存在多列数据,0代表第一列数据,1代表第二列,以此类推
    price.append(price_data)  # 存储第二列所有数据
print("第一列所有数据:",name)
print("第二列所有数据:",price)
name_list=[]   #名称去重
for i in name:
    if not i in name_list:
        name_list.append(i)
print("名称列去重:",name_list)
print("去重后总行数:",len(name_list))

workbook = xlwt.Workbook(encoding='ascii')
worksheet = workbook.add_sheet('My Worksheet')   #保存文件的sheel页名称

i = -1
for b in name_list:
    i = i+1
    worksheet.write(i, 0, label=b)
    name_index = []
    price_list = []
    for index, nums in enumerate(name):
        if nums == b:
            name_index.append(index)
            if price[index] not in price_list:
                price_list.append(price[index])
    print(price_list)
    j = 0
    for price_i in price_list:
        j = j+1
        worksheet.write(i, j, label=price_i)
workbook.save('处理火车站表1结果.xls')  #保存表名称

 



这篇关于python读写excel文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程