Python实用记录(十):获取excel数据并通过列表的形式保存为txt文档、xlsx文档、csv文档

简介: 这篇文章介绍了如何使用Python读取Excel文件中的数据,处理后将其保存为txt、xlsx和csv格式的文件。

1. 获取excel文档中的每一个数据并保存为数组

在这里插入图片描述

import openpyxl
import pandas as pd
import numpy as np

def Read_Excel(Excelname,sheet):
    '''
    作用:读取excel表格
    load_workbook 模块读取 excel 文件中对应的"修改"表中的数据,封装为列表并返回
    '''
    excel = openpyxl.load_workbook(filename=Excelname)
    # 获取sheet对应的excel数据 分别有两个一个是data,一个是Sheet1
    reult=excel[sheet]
    return reult
def Deal_data(reult):
    # 最小行 最大行 最小列 最大列
    print(reult.min_row, reult.max_row, reult.min_column, reult.max_column)

    Julei_a1=(70.72450+58.41271+79.55004+80.25528+90.63146)/5
    Julei_a3=(77.85307+67.64918+78.36915+53.75346+89.09208)/5
    Julei_a5=(59.73232+74.38533+85.66948+85.93039+74.38057)/5
    print(Julei_a5,Julei_a3,Julei_a1)

    store=[]
    for i in range(reult.min_row+1,reult.max_row+1):
        Customer = get_Value(reult,'A'+str(i)) 
        Brand_type = get_Value(reult,'B'+str(i)) 
        a1 = get_Value(reult,'C'+str(i)) 
        a1=(Julei_a1 if int(a1)>100 else a1)
        a2 = get_Value(reult,'D'+str(i)) 
        a3 = get_Value(reult,'E'+str(i)) 
        a3=(Julei_a3 if int(a3)>100 else a3)
        a4 = get_Value(reult,'F'+str(i))
        a5 = get_Value(reult,'G'+str(i))
        a5=(Julei_a5 if int(a5)>100 else a5) 
        a6 = get_Value(reult,'H'+str(i)) 
        a7 = get_Value(reult,'I'+str(i)) 
        a8 = get_Value(reult,'J'+str(i)) 
        # print(a1)
        if int(a1)<0 or int(a2)<0 or int(a3)<0 or int(a4)<0 or int(a5)<0 or int(a6)<0 or int(a7)<0 or int(a8)<0 : # 判断是否有负数
            print('a1-a8存在负数')
        if int(a1)>100 or int(a2)>100 or int(a3)>100 or int(a4)>100 or int(a5)>100 or int(a6)>100 or int(a7)>100 or int(a8)>100 : # 判断是否有大于100的数
            print('a1-a8存在大于100的数 \n')
        B1 = get_Value(reult,'k'+str(i))
        B2 = get_Value(reult,'L'+str(i))
        B3 = get_Value(reult,'M'+str(i)) 
        B4 = get_Value(reult,'N'+str(i)) 
        B5 = get_Value(reult,'O'+str(i)) 
        B6 = get_Value(reult,'P'+str(i)) 
        B7 = get_Value(reult,'Q'+str(i)) 
        B7 = (0 if B7=='#NULL!' else B7)
        if B7=='#NULL!':
            print('B7 存在 #NULL 该值为:{}\n'.format(B7))
        B8 = get_Value(reult,'R'+str(i)) 
        B9 = get_Value(reult,'S'+str(i)) 
        B10 = get_Value(reult,'T'+str(i))
        B11 = get_Value(reult,'U'+str(i)) 
        B12 = get_Value(reult,'V'+str(i)) 
        B13 = get_Value(reult,'W'+str(i))
        B14 = get_Value(reult,'X'+str(i)) 
        B15 = get_Value(reult,'Y'+str(i))
        B16 = get_Value(reult,'Z'+str(i)) 
        B17 = get_Value(reult,'AA'+str(i)) 
        Purchase_think = get_Value(reult,'AB'+str(i)) 
        print(Customer,Brand_type,a1,a2,a3,a4,a5,a6,a7,a8,B1,B2,B3,B4,B5,B6,B7,B8,B9,B10,B11,B12,B13,B14,B15,B16,B17,Purchase_think)
        store.append([Customer,Brand_type,a1,a2,a3,a4,a5,a6,a7,a8,B1,B2,B3,B4,B5,B6,B7,B8,B9,B10,B11,B12,B13,B14,B15,B16,B17,Purchase_think])
    return store

def get_Value(wb, tag):
    '''
    输入:获取相应单元格的数据
    wb为表格对象
    tag为单元格标签
    输出:对应单元格的数据
    '''
    return wb[tag].value

if __name__ == '__main__':
    # excel_path='F:\epycharm\HSB_match\excel_file\Whole_data.xlsx'
    new_Excel_path=r'F:\epycharm\HSB_match\excel_file\predict_data.xlsx'
    result_data = Read_Excel(new_Excel_path, 'Sheet1')  # Sheet1 data
    store=Deal_data(result_data) # 将每一行的数据保存为数组

2. txt

        """保存为txt"""
        f = open('F:\epycharm\HSB_match\excel_file\After_Deal_txt.txt','a')
        f.write(str(Customer)+' '+str(Brand_type)+
                ' '+str(a1)+' '+ str(a2)+' '+str(a3)+' '+str(a4)+' '+str(a5)+' '+str(a6)+' '+str(a7)+' '+str(a8)+
                ' '+str(B1)+' '+str(B2)+' '+str(B3)+' '+str(B4)+' '+str(B5)+' '+str(B6)+' '+str(B7)+' '+str(B8)+' '+str(B9)+' '+str(B10)+
                ' '+str(B11)+' '+str(B12)+' '+str(B13)+' '+str(B14)+' '+str(B15)+' '+str(B16)+' '+str(B17)+
                ' '+str(Purchase_think))
        f.write('\n')

3. xlsx

def savenpyasexcel(ndarray,output):
    #ndarray是数组,output是保存的文件位置
    data_df = pd.DataFrame(ndarray)  # 关键1,将ndarray格式转换为DataFrame
    rows,cols = ndarray.shape
    print(rows,cols)
    # 更改表的索引
    data_index = []
    for i in range(rows):
        data_index.append(i)
    data_df.index = data_index
    # 更改表的索引
    data_indexs = []
    for i in range(cols):
        data_indexs.append(i)
    data_df.index = data_index
    data_df.columns = data_indexs

    # 将文件写入excel表格中
    writer = pd.ExcelWriter(output)
    data_df.to_excel(writer, 'page_1',
                     float_format='%.4f')  # 关键3,float_format 控制精度,将data_df写到hhh表格的第一页中。若多个文件,可以在page_2中写入
    writer.save()  # 关键4
    return 1
"""保存为excel的xlsx"""
savenpyasexcel(np.array(store),new_Excel_path) # 保存为excel

4. csv

np.savetxt("deal_data.csv", np.array(store), delimiter=",")
目录
相关文章
|
2月前
|
XML 数据格式 Python
从手动编辑到代码生成:Python 助你高效创建 Word 文档
本文介绍如何用Python实现Word文档自动化生成,结合python-docx、openpyxl和matplotlib库,高效完成报告撰写、数据插入与图表生成,大幅提升办公效率,降低格式错误,实现数据驱动的文档管理。
557 2
|
2月前
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
236 1
|
2月前
|
开发者 Python
Python列表推导式:优雅与效率的完美结合
Python列表推导式:优雅与效率的完美结合
420 116
|
2月前
|
Python
Python列表推导式:简洁与高效的艺术
Python列表推导式:简洁与高效的艺术
458 119
|
2月前
|
Python
Python列表推导式:简洁与高效的艺术
Python列表推导式:简洁与高效的艺术
|
2月前
|
索引 Python
Python 列表切片赋值教程:掌握 “移花接木” 式列表修改技巧
本文通过生动的“嫁接”比喻,讲解Python列表切片赋值操作。切片可修改原列表内容,实现头部、尾部或中间元素替换,支持不等长赋值,灵活实现列表结构更新。
151 1
|
2月前
|
大数据 开发者 Python
Python列表推导式:简洁与高效的艺术
Python列表推导式:简洁与高效的艺术
|
SQL 安全 关系型数据库
python 从txt导数据到mysql
!/usr/bin/python encoding:utf-8 import MySQLdb db = MySQLdb.connect("127.0.0.
959 0
|
3月前
|
数据采集 机器学习/深度学习 人工智能
Python:现代编程的首选语言
Python:现代编程的首选语言
323 102
|
3月前
|
数据采集 机器学习/深度学习 算法框架/工具
Python:现代编程的瑞士军刀
Python:现代编程的瑞士军刀
349 104

推荐镜像

更多