簡體   English   中英

Openpyxl - 合並由字符串分隔的空列單元格

[英]Openpyxl - Merge Empty Column Cells Delimited by String

我一直在做一些大數據工作,我一直在編寫一個腳本來自動將 15,000 多行的格式設置為 csv 到格式化的 excel 文件中。 我一直在使用 Openpyxl 進行大部分格式化工作。

我需要將主機名列中的服務器名稱單元格與其下方的空單元格合並,但似乎無法正常工作。 在下表中,我需要將Dev Server與其下方的所有空單元格合並(以在RAS Server處停止)。 然后將RAS 服務器與其下方的空單元格合並,並將Prod 服務器與其下方的空單元格合並。

我遇到的問題是我似乎無法指定正確for循環來標識帶有字符串的單元格,遍歷它下面的每個單元格(與空單元格合並),然后停止並開始新的合並包含字符串的下一個單元格處的單元格。

指定的參數/單元格編號在這里不起作用 - 實際表格有 15,000 多行,每台服務器上“安裝的軟件”的數量在每台服務器 25-200 多個范圍內。 為了讓事情變得更好,真實的服務器名稱也沒有一致的命名模式或方案。

這可能嗎? 任何幫助或指導將不勝感激。

主機名 安裝的軟件
開發服務器 微軟字
微軟 Excel
微軟團隊
視覺工作室代碼
Discord
RAS服務器 微軟字
Spotify 音樂
Log4j
生產服務器 Adobe Photoshop
虛幻引擎
Adobe PDF 閱讀器
蒸汽
Adobe Illustrator 軟件
超級V
wb = openpyxl.load_workbook("Test.xlsx")  # Load Workbook
ws = wb["Sheet1"]                         # Load Worksheet

    total_rows = []  # Used to enumerate the total number of rows
                     # in the Worksheet

    for i in range (1,20000):
        if ws["B" + str(i)].value != None:
            total_rows.append(i)  # If the cell has a string, the
                                  # cell row number is appended to 
                                  # total_rows.  Indexing the last 
                                  # number is total_rows will give
                                  # you the total number of rows
    
    cells_with_strings = []
    for i in range (1,(total_rows[-1])):
        if ws["A" + str(i)].value != None:
            cells_with_strings.append(int(i))
            # Iterates through each cell in column A, and appends
            # the row numbers of cells containing text to cells_with_strings
    
    merge_cell_range = len(cells_with_strings) - 1
    for i in range (0, (merge_cell_range)):
        ws.merge_cells("A" + str(cells_with_strings[i]) + ":" + "A" + str((cells_with_strings[(i+1)])-1))
        # Using the values in cell_with_strings, it merges the cells in the rows
        # represented by the values in cells_with_strings.  This works for all 
        # merges except for the last merge.
    
    final_merge = []
    for i in range ((cells_with_strings[-1]), ((cells_with_strings[-1]) + 9999)):
        if ws["B" + str(i)].value != None:
            final_merge.append(int(i))
    ws.merge_cells("A" + str(final_merge[0]) + ":" + "A" + str(final_merge[-1]))
    # The last row merge requires different code to the iteration merge.

wb.save("Test.xlsx")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM