Python openpyxl 如何将行值移动到当前位置 - 1?

Python openpyxl how do I shift row values to current position - 1?

我正在尝试格式化多个 excel 2007 文件,这些文件将由单独的 ETL 程序使用。我只需要将行值向上移动一级。所以第 3 行的值,我想转移到第 2 行。

请耐心等待,我是 python 和 openpyxl 的菜鸟。

我尝试遍历工作表并在我使用的循环内 ws.cell(param, param) 我将行设置为 -1 但这似乎不起作用

我还尝试遍历行,并在循环内创建另一个迭代,它将从父循环开始 max row-1 并将值从子循环行分配给主循环行,但这似乎不是工作也许我错过了一些东西。

创建一个名为 'demo.py' 的新文件并复制以下内容 进去。这应该做一些接近你想要的事情。希望评论(连同先决条件谷歌搜索)会 给你一个很好的指示,说明发生了什么。这将需要一个现有的电子表格和您要向上移动的起始行。它将执行该操作,如果起始行 # 小于现有行,它将添加一个空白行并将其余源行附加到它们的原始行号。为了安全起见,它会将结果转储到新的工作簿中。

import sys
import os
from openpyxl import load_workbook, Workbook

# check that you have 2 command line arguments to use
if len(sys.argv)!=3:
   sys.exit("Usage demo.py xls_filename start_line")

# ensure you have an existing file
if not os.path.isfile(sys.argv[1]):
   sys.exit("input file does not exist")
excelFile=sys.argv[1]

# make sure the starting row is a number!
if not (sys.argv[2]).isdigit(): 
   sys.exit("2nd argument must be a digit")
num=int(sys.argv[2])

# make sure your extension is okay 
root,ext = os.path.splitext(excelFile)
if not ext in ['.xls','.xlsm','.xlsx','.xlsb']:
   sys.exit("%s does not have an allowable excel extension"%excelFile)
newExcelFile=root + '_new' + ext

# open the source (1) and destination (2) workbooks & worksheets
wb1 = load_workbook(excelFile)
wb2 = Workbook()
ws1 = wb1.active
ws2 = wb2.active

# move each source row up one in the destination 
# starting from row 1 to num
num=min(num,ws1.max_row)
for i in range(1,num):
  ws2.append(ws1.rows[i])

if num<ws1.max_row:
  # append a blank row
  ws2.append(tuple())
  # copy the rest of the rows
  for i in range(num,ws1.max_row):
    ws2.append(ws1.rows[i])

# save the destination workbook
wb2.save(newExcelFile)

请注意,您将丢失源工作表的第一行 - 这可能不是您想要的。

我必须在这里添加一个免责声明:我不能保证它的 robustness/completeness 因为我的 python 已经生锈了而且我只用过 'win32com' 来做类似的事情.我会把进一步的开发(和调试)留给你,但如果有问题请告诉我。

from openpyxl import Workbook
from openpyxl import load_workbook

wb = load_workbook("sample.xlsx")

ws1 = wb.active
ws2 = wb.create_sheet("modifiedSheet")

start_row = 3
start_col = 1

for row in ws1.iter_rows(min_row=start_row):
    for cell in row:
        # print(cell.value)
        ws2.cell(row = start_row-2, column = start_col, value=cell.value) # start_row - 2 will assign the value to the same column up 2 rows
        start_col += 1 # increment the column, for use of destination sheet
    start_row += 1 # increment the column, for use of destination sheet
    start_col = 1 # reset to first column after row processing

wb.save("modified.xlsx")

这不是动态的,但可以完成工作

可以使用openpyxl move_range函数。

ws.move_range("D4:F10", rows=-1, cols=2)

这会将 D4:F10 范围向上移动一行并向右移动两列。

希望对您有所帮助:)