1. 程式人生 > 其它 >Python 分部分項 資料處理 桂柳

Python 分部分項 資料處理 桂柳

excel格式

python程式碼

import os
import openpyxl
from openpyxl import Workbook
from copy import deepcopy
from openpyxl.utils import get_column_letter


# 原文:https://www.cnblogs.com/liuda9495/p/9039732.html



workbook2 = Workbook()


def create_worksheet(path):

    #path='test1.xlsx'
    workbook = openpyxl.load_workbook(path)# 載入excel
    name_list = workbook.sheetnames# 所有sheet的名字
    
    
    for index, value in enumerate(name_list):
        print(index, value)    
        
        worksheet = workbook[name_list[index]]# 讀取第一個工作表

        # 獲取所有 合併單元格的 位置資訊
        # 是個可迭代物件,單個物件型別:openpyxl.worksheet.cell_range.CellRange
        # print後就是excel座標資訊
        m_list = worksheet.merged_cells

        l = deepcopy(m_list)# 深拷貝

        # 拆分合並的單元格 並填充內容
        for m_area in l:
            
            # 這裡的行和列的起始值(索引),和Excel的一樣,從1開始,並不是從0開始(注意)
            r1, r2, c1, c2 = m_area.min_row, m_area.max_row, m_area.min_col, m_area.max_col
                
            worksheet.unmerge_cells(start_row=r1, end_row=r2, start_column=c1, end_column=c2)
            #print('區域:', m_area, '  座標:', r1, r2, c1, c2)
            
            # 獲取一個單元格的內容
            first_value = worksheet.cell(r1, c1).value

            # 資料填充
            for r in range(r1, r2+1):# 遍歷行        
                if c2 - c1 > 0:# 多個列,遍歷列
                    for c in range(c1, c2+1):
                        worksheet.cell(r, c).value = first_value
                else:# 一個列
                    worksheet.cell(r, c1).value = first_value


        # 刪除行
        worksheet.delete_rows(2)
        worksheet.delete_rows(1)

        
        worksheet2 = workbook2.create_sheet(name_list[index])
        for x in range(worksheet.max_row):# 首列批量填充資料
            r = x+1
            for y in range(worksheet.max_column):
                c = y+1
                worksheet2.cell(r, c).value = worksheet.cell(r, c).value
        

        # 列寬度自適應
        for y in range(worksheet.max_column):
            column_width = 10
            for x in range(worksheet.max_row):
                c = y+1
                r = x+1
                cellLength = 10
                cellValue = worksheet.cell(r, c).value
                if cellValue is not None:
                    if type(cellValue) == int:
                        cellLength = 10
                    else:
                        cellLength = len(cellValue)
                if cellLength > column_width:
                    column_width = cellLength
            column_NameEn = get_column_letter(y + 1)
            worksheet2.column_dimensions[column_NameEn].width = column_width * 2




def each_files():    
    pathDir =  os.listdir('./files/')
    for index, value in enumerate(pathDir):
        filepath2 = './files/' + value
        print(filepath2)
        create_worksheet(filepath2)
        


each_files()
workbook2.save('test2.xlsx')