Python 中是否有使用 Openpyxl 将所有工作表的行移动到特定行号的方法?

Is there a way to move the rows of all the sheets to specific row number using Openpyxl in Python?

我正在使用 Openpyxl 读取 excel 文件并在 txt 文件中获得我想要的输出(不是下面显示的所有代码,因为它是不相关的)。下面是我读取 excel file.The 测试文件的代码,其中包含 3 sheets.As 你可能已经注意到了,我正在跳过 excel [=60] 中的第一个 sheet =] other sheets 有我需要的数据。我感兴趣的列是“字段名称”和“类型”。但是,如下面的代码片段所示,这些行位于 sheet 1 中的第 5 行和 sheet 2 中的第 8 行。我想知道我是否可以让两个 sheet 都具有“字段名称”和“类型”从 7 开始(而不是手动操作)?是否可以执行任何搜索以确保我在第 7 行有“字段名称”和“类型”,如果没有,我可以在同一个 sheet 中更正它而不是创建 [=68 的副本=] ?我检查了here,不幸的是找不到解决方案。从第 7 行开始的原因是因为我从第 8 行开始从 sheet 中获取数据并将其添加到 txt 文件中。

注意:以下快照仅为演示。我的原始 excel 文件包含 10 多个 sheet 具有相同问题,即“字段名称”和“类型”不是从第 7

行开始

在此先感谢您的帮助!

Python代码:

from openpyxl import load_workbook

data_file='test.xlsx'

# Load the entire workbook.
wb = load_workbook(data_file)
 
skip = True
for ws in wb.worksheets:
    if skip == True:
        skip = False
    else:
        for i in range(7, ws.max_row+1):  
            name = ws.cell(row=i, column=1).value
            print(i, name)
            name1=ws.cell(row=i, column=2).value
            print(name1)
            ....... my other code

Sheet 1

Sheet 2:

Sheet SO 注释后输出:

Sheet 1:

Sheet 2:

您可以使用 insert_rows()delete_rows()...

来实现

请注意,您需要在拥有 added/deleted 行后保存文件。

from openpyxl import load_workbook

data_file='test.xlsx'

# Load the entire workbook.
wb = load_workbook(data_file)
 
skip = True
for ws in wb.worksheets:
    if skip == True:
        skip = False
    else:
        CurrentRow = 0
        for row in ws.iter_rows(max_col=2):
            if row[0].value == 'Field Name' and row[1].value == 'Type':
                CurrentRow = row[0].row
                break            
            else:
                pass
        if CurrentRow > 7:
            ws.delete_rows(7, CurrentRow - 7)
        elif CurrentRow < 7 and CurrentRow > 0:
            ws.insert_rows(CurrentRow, 7 - CurrentRow)
wb.save('test.xlsx')

处理tables 您的 sheet 中的输入数据看起来是 excel Table。您可以通过选择范围和 right-clicking(快速分析下应该有 table 选项)来检查这一点。如果是这种情况,您有两个选择。

  1. Select table 中的一个单元格 >> 右键单击​​ >> Table >> 转换为范围。那么原始代码将运行。不知道行不行。
  2. 下面写的代码将在您的所有 sheet 都具有 table 时起作用。请注意,我正在考虑每个 sheet 中只有一个 table。此外,样式设置为您在上面的图片中共享的蓝色格式。从
  3. 借用代码
from openpyxl import load_workbook
from openpyxl.worksheet.table import Table, TableStyleInfo
style = TableStyleInfo(name="TableStyleMedium9", showFirstColumn=False, showLastColumn=False, showRowStripes=True, showColumnStripes=False)

def colnum_string(n):
    string = ""
    while n > 0:
        n, remainder = divmod(n - 1, 26)
        string = chr(65 + remainder) + string
    return string

#data_file='test.xlsx'
data_file = input("Please provide the name of file you want to process: ")

# Load the entire workbook.
wb = load_workbook(data_file)

skip = True
for ws in wb.worksheets:
    if skip == True:
        skip = False
    else:
        CurrentRow = 0
        tablelen = 0
        for row in ws.iter_rows(max_col=2):
            if row[0].value == 'Field Name' and row[1].value == 'Type':
                CurrentRow = row[0].row
                tablelen = ws.max_row - CurrentRow
                break            
            else:
                pass
        if CurrentRow > 7:
            ws.delete_rows(7, CurrentRow - 7)
            resTable = Table(displayName=ws.tables.items()[0][0], ref="A7:{}{}".format("B", 7+tablelen))
            resTable.tableStyleInfo = style
            ws._tables[ws.tables.items()[0][0]] = resTable

        elif CurrentRow < 7 and CurrentRow > 0:
            ws.insert_rows(CurrentRow, 7 - CurrentRow)
            resTable = Table(displayName=ws.tables.items()[0][0], ref="A7:{}{}".format("B", 7+tablelen))
            resTable.tableStyleInfo = style
            ws._tables[ws.tables.items()[0][0]] = resTable
           
#wb.save('test.xlsx')
wb.save(data_file.split('.')[0] + "_updated." + data_file.split('.')[1])

新请求 - 读取所有 xlsx 文件

from openpyxl import load_workbook
from openpyxl.worksheet.table import Table, TableStyleInfo
style = TableStyleInfo(name="TableStyleMedium9", showFirstColumn=False, showLastColumn=False, showRowStripes=True, showColumnStripes=False)

def colnum_string(n):
    string = ""
    while n > 0:
        n, remainder = divmod(n - 1, 26)
        string = chr(65 + remainder) + string
    return string

import os
ALLOWED_EXTENSIONS = set(['xlsx'])

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

MyPWD = os.getcwd()
for filename in os.listdir(MyPWD):
    path = os.path.join(MyPWD, filename)
    if os.path.isfile(path) and allowed_file(filename):

        #data_file='test1.xlsx'
        #data_file = input("Please provide the name of file you want to process: ")
        # Load the entire workbook.
        wb = load_workbook(filename)

        skip = True
        for ws in wb.worksheets:
            if skip == True:
                skip = False
            else:
                CurrentRow = 0
                tablelen = 0
                for row in ws.iter_rows(max_col=2):
                    if row[0].value == 'Field Name' and row[1].value == 'Type':
                        CurrentRow = row[0].row
                        tablelen = ws.max_row - CurrentRow
                        break            
                    else:
                        pass

                if CurrentRow > 7:
                    ws.delete_rows(7, CurrentRow - 7)
                    resTable = Table(displayName=ws.tables.items()[0][0], ref="A7:{}{}".format("B", 7+tablelen))
                    resTable.tableStyleInfo = style
                    ws._tables[ws.tables.items()[0][0]] = resTable
                elif CurrentRow < 7 and CurrentRow > 0:
                    ws.insert_rows(CurrentRow, 7 - CurrentRow)
                    resTable = Table(displayName=ws.tables.items()[0][0], ref="A7:{}{}".format("B", 7+tablelen))
                    resTable.tableStyleInfo = style
                    ws._tables[ws.tables.items()[0][0]] = resTable

        #wb.save('test2.xlsx')
        wb.save(filename.split('.')[0] + "_updated." + filename.split('.')[1])