【发布时间】: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")
【问题讨论】:
-
很遗憾没有。如果我以仅数据形式打开,它根本不会读取数据。关于如何更改它的任何想法?