【问题标题】:Openpyxl copy and paste as values in new workbookOpenpyxl复制并粘贴为新工作簿中的值
【发布时间】:2021-07-31 11:36:20
【问题描述】:

我正在尝试使用 openpyxl 将源文件中的前 100 行复制到新的目标文件。我的源文件有公式,但我想复制并粘贴为新工作簿中的值。当我添加 data_only=True,(见下面的代码)时,它只复制我的源表的值,因此不复制公式单元格中的数据 - 这些在目标文件中只是空的。如何复制所有内容并将其作为值粘贴到目标工作表中?

WB1 = load_workbook("sample_book.xlsx")
WB1_WS1 = WB1["Ark2"]
WB2 = Workbook()

#Create new worksheet in new workbook
for i in range(1,2):
    WB2.create_sheet(f"WS{i}")
    
#Delete first sheet
WB2.remove(WB2.worksheets[0])

#Define the ranges and sheets 
copy_ranges = [100]
copy_to_sheets = ["WS1"]

# Copy the values from the rows in WB1 to WB2
for i in range (len(copy_ranges, data_only=True)):
    #Set the sheet to compy to
    ws = WB2[copy_to_sheets[i]]
    #initialize row offset 
    offset = 1
    for s in range (i):
        offset+=copy_ranges[s]
        
    #copy the row and append 
    for j in range(offset, offset + copy_ranges[i]):
        #if j==0:
        #  continue 
        for row in WB1_WS1.iter_rows(min_row=j,max_row=j,min_col=1,max_col=WB1_WS1.max_column):
            values_row = [cell.value for cell in row]
        ws.append(values_row)

#save
WB2.save("WB2.xlsx")

【问题讨论】:

标签: python openpyxl


【解决方案1】:

您使用 Len() 不正确。 Len() 返回列表的长度。 copy_ranges 是一个 1 项的列表,所以 Len(copy_ranges) = 1。如果要访问列表中的第一项,则需要使用索引:Len(copy_ranges[0]) = 100

我没有完全遵循“偏移”代码部分,并且存在问题

offset = 1
    for s in range (i):
        offset+=copy_ranges[s]

在 i > 1 的任何迭代中,s 将 > 1,这意味着 offset+=copy_ranges[s] 将引发 IndexError,因为 copy_ranges 是一个单项列表,而您正试图访问一个不存在的元素。

这里有两种方法可以复制前 100 行:

如果你想要WB2中的公式,不要传入data_only参数。

## VERSION 1: Output will have formulas from WB1

WB1 = load_workbook('int_column.xlsx')
WB1_WS1 = WB1['Sheet']

WB2 = Workbook()
WB2_WS1 = WB2.active # get the active sheet, so you don't need to create then delete one

# copy rows
for x, row in enumerate(WB1_WS1.rows):
    if x < 100: # only copy first 100 rows
        num_cells_in_row = len(row)
        for y in range(num_cells_in_row):
            WB2_WS1.cell(row=x + 1, column=y + 1).value = WB1_WS1.cell(row=x + 1, column=y + 1).value

WB2.save('copied.xlsx')

如果设置data_only=True,则WB1中单元格的显示值将复制到WB2中。

## VERSION 2: Output will have value displayed in cells in WB1

WB1 = load_workbook('int_column.xlsx', data_only=True)
WB1_WS1 = WB1['Sheet']

WB2 = Workbook()
WB2_WS1 = WB2.active # get the active sheet, so you don't need to create then delete one

# copy rows
for x, row in enumerate(WB1_WS1.rows):
    if x < 100: # only copy first 100 rows
        num_cells_in_row = len(row)
        for y in range(num_cells_in_row):
            WB2_WS1.cell(row=x + 1, column=y + 1).value = WB1_WS1.cell(row=x + 1, column=y + 1).value

WB2.save('copied.xlsx')

【讨论】:

    猜你喜欢
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多