Python_ how to operate the Excel file and rearrange the data.

I haven't written an article on CSDN for a long time, and now I am not just doing Unity, nor just staying in the initial stage of development. In addition to working for so long, Unity, UE4, Python, Flutter, Playcanvas, ThreeJS, etc. are all working on it. There are too many things, and the energy is not enough, so I will stop writing. I also thank CSDN, which is a great help on my program path!
In the future, I will work hard as a product manager.

Code purpose: Change the horizontal data structure in EXCLE to a vertical structure.
The code is pasted directly, and there are few explanations. The purpose of this article is mainly for personal records, which is convenient for pasting and use later. Please forgive me if there are any unsatisfactory places.

from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.styles import colors
from openpyxl.styles import Color
from openpyxl.styles import Border, Side, PatternFill, Font, GradientFill, Alignment

import datetime

#获取generator类型数据的长度
def get_length(generator):
    if hasattr(generator,"__len__"):
        return len(generator)
    else:
        return sum(1 for _ in generator)

# 进行Excle处理的类
class ExcleTool:

    #Excle文件的全路径
    excle_file_Path =''

    def __init__(self,excle_file_Path):
        self.excle_file_Path = excle_file_Path

    #读取文件
    def readExcle(self):
        #打开工作表
        wb = load_workbook(self.excle_file_Path)
        print(wb.sheetnames)
        return wb

    def updateExcle(self,wb):
        # 选择工作表的第一个tab页
        ws1 = wb[wb.sheetnames[0]]
        # 并创建一个新的Tab页,用于存放新的数据。
        ws_new = wb.create_sheet("right") 


        start_row = 2
        ws1_rows = get_length(ws1.rows)
        ws1_columns = get_length(ws1.columns)

        print("行: " + str(ws1_rows)+ " : " + "列: " + str(ws1_columns))

        # 以下代码的业务背景为:老的数据排列是横向的,比如一行里面就有 姓名:x1、x2,性别:男、女等
        # 以下逻辑就是把这种横向数据改为数项的结构。
        # 附近我会放上已经处理好的数据,可以更方便了解做了什么。
        # 理解到有什么改变后,看下面代码会简单些。
        # 但可能你的业务逻辑不同,所以删除也行。我会把 excel主要操作的代码注释,业务方便的就不细说了。 
        ws_new_curr_row = 1
        data_range = 12  # 正确数据的范围。11列为一行数据
        for row in ws1.iter_rows(min_row=start_row, max_row=ws1_rows, max_col=1):
            for cell in row:
                
                #读取一个格子的数据,如果没有,则会赋值value 的值。
                _ = ws_new.cell(row=ws_new_curr_row,column=1,value = cell.value)
                # 设置格子中字体大小、颜色、加粗
                _ .font = Font(b=True, size=14,color="00FFFFFF")
                # 设置格子的内容左对齐
                _.alignment = Alignment(horizontal="left", vertical="center")
                # 设置格子的背景色为渐变色
                _.fill = fill = GradientFill(stop=("00000080", "003366FF"))

                offest = 2

                new_col_index =1
                for col_index in range(offest,ws1_columns):
                    yu = (col_index-offest)%data_range
                    #11的整数
                    if(yu == 0):
                        ws_new_curr_row+=1
                        new_col_index =1

                    # 取一个格子的数据
                    ws1_d = ws1.cell(row=cell.row,column=col_index)

                   # 为新的Tab页中格子进行赋值
                    new_ws = ws_new.cell(row=ws_new_curr_row,column=new_col_index,value = ws1_d.value)
                    
                    # 更改对齐方式,第一列的做对齐,剩下的列为剧中对齐。
                    new_ws.alignment = Alignment(horizontal=("left" if (yu == 0) else "center"), vertical="center")

                    #下一列
                    new_col_index +=1
                   # print('行数据 %s'%(ws1_d.value))
                
                ws_new_curr_row +=3

        #完成操作后记着要保存
        wb.save("newExcel.xlsx")
        print(' OK')



excletool = ExcleTool('datatable.xlsx')

wb = excletool.readExcle()
excletool.updateExcle(wb)

The files are for study only, not for commercial use or distribution.

Processed file address
Free download: https://download.csdn.net/download/KiTok/77853134

Guess you like

Origin blog.csdn.net/KiTok/article/details/122689787