我编写了一个函数,它可以使用 openpyxl 在电子表格或整个 2D 表中的任何位置插入整行。
函数的每一行都用注释解释,但如果你只想插入一行,只需让你的行等于 [row]。即如果 row = [1,2,3,4,5] 然后将您的输入设置为 [[1,2,3,4,5]]。如果您希望将此行插入电子表格的第一行 (A1),则 Start = [1,1]。
您确实可以覆盖文件名,如底部的示例所示。
def InputList(Start, List): #This function is to input an array/list from a input start point; len(Start) must equal 2, where Start = [1,1] is cell 1A. List must be a two dimensional array; if you wish to input a single row then this can be done where len(List) == 1, e.g. List = [[1,2,3,4]]
x = 0 #Sets up a veriable to go through List columns
y = 0 #Sets up a veriable to go through List rows
l = 0 #Sets up a veriable to count addional columns against Start[1] to allow for column reset on each new row
for row in List: #For every row in List
l = 0 #Set additonal columns to zero
for cell in row: #For every cell in row
ws.cell(row=Start[0], column=Start[1]).value = List[y][x] #Set value for current cell
x = x + 1 #Move to next data input (List) column
Start[1] = Start[1] + 1 #Move to next Excel column
l = l + 1 #Count addional row length
y = y + 1 #Move to next Excel row
Start[0] = Start[0] + 1 #Move to next Excel row
x = 0 #Move back to first column of input data (ready for next row)
Start[1] = Start[1] - l #Reset Excel column back to orignal start column, ready to write next row
在第 7 行开头插入单行的示例:
from openpyxl import load_workbook
wb = load_workbook('New3.xlsx')
ws = wb.active
def InputList(Start, List): #This function is to input an array/list from a input start point; len(Start) must equal 2, where Start = [1,1] is cell 1A. List must be a two dimensional array; if you wish to input a single row then this can be done where len(List) == 1, e.g. List = [[1,2,3,4]]
x = 0 #Sets up a veriable to go through List columns
y = 0 #Sets up a veriable to go through List rows
l = 0 #Sets up a veriable to count addional columns against Start[1] to allow for column reset on each new row
for row in List: #For every row in List
l = 0 #Set additonal columns to zero
for cell in row: #For every cell in row
ws.cell(row=Start[0], column=Start[1]).value = List[y][x] #Set value for current cell
x = x + 1 #Move to next data input (List) column
Start[1] = Start[1] + 1 #Move to next Excel column
l = l + 1 #Count addional row length
y = y + 1 #Move to next Excel row
Start[0] = Start[0] + 1 #Move to next Excel row
x = 0 #Move back to first column of input data (ready for next row)
Start[1] = Start[1] - l #Reset Excel column back to orignal start column, ready to write next row
test = [[1,2,3,4]]
InputList([7,1], test)
wb.save('New3.xlsx')