2017-07-05 258 views
0

嗨,所以我想將W7:W46列複製並粘貼到另一個工作表中。我到目前爲止的代碼,使用OpenPyxl複製粘貼列範圍

col_j = New_Burden['W'] 
for idx, cell in enumerate(col_j,1): 
    ws1.cell(row = idx, column = 10).value = cell.value 

能夠複製整個列,但不幸的是也傳輸各種標題。一個解決方案,我已經試過是:

for row in New_Burden['W7:W46']: 
    for cell in row: 
     ws1.cell(row = 2, column = 10).value = cell.value 

但是,這僅複製W7

複製的
+0

你從哪裏得到'idx'? – frankyjuang

+0

@frankyjuang idx只是一個變量名。 –

+0

因爲'row'和'column'沒有提交。 –

回答

1

第一值範圍(['W7:W46'])從一個工作表到另一個工作表:
如果範圍是重疊,在同一個Worksheet中也是可以的。

from openpyxl import Workbook 
# Create a new Workbook 
wb = Workbook() 
ws = wb.worksheets[0] 

from openpyxl.utils import range_boundaries 
# Define start Range(['J2']) in the new Worksheet 
min_col, min_row, max_col, max_row = range_boundaries('J2') 

# Iterate Range you want to copy 
for row, row_cells in enumerate(New_Burden['W7:W46'], min_row): 
    for column, cell in enumerate(row_cells, min_col): 
     # Copy Value from Copy.Cell to given Worksheet.Cell 
     ws.cell(row=row, column=column).value = cell.value 

如果你想要做上述多個不同的列, 使用上面的function

def copy_range(source_range, target_start): 
    # Define start Range(target_start) in the new Worksheet 
    min_col, min_row, max_col, max_row = range_boundaries(target_start) 

    # Iterate Range you want to copy 
    for row, row_cells in enumerate(New_Burden[source_range], min_row): 
     for column, cell in enumerate(row_cells, min_col): 
      # Copy Value from Copy.Cell to given Worksheet.Cell 
      ws.cell(row=row, column=column).value = cell.value 

for source_range, target_start in [('W7:W46','J2'), ('Y7:Y46','A2')]: 
    copy_range(source_range, target_start) 

測試與Python 3.4.2 - openpyxl:2.4 .1 - LibreOffice:4.3.3.2

相關問題