Python 3X Win32COM:从工作簿中的工作表中复制二手单元



我的工作簿中有6个工作表。我想从5个工作表中复制数据(所有使用的单元格除外(,然后将它们粘贴到第一个工作表中。适用的代码段:

`

excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(mergedXL)
wsSIR = wb.Sheets(1)
sheetList = wb.Sheets
for ws in sheetList:
        used = ws.UsedRange
        if ws.Name != "1st sheet":
            print ("Copying cells from "+ws.Name)
            used.Copy()

`under.copy((将复制所有使用的单元格,但是我不希望任何工作表中的第一行。我希望能够从每个纸上复制并将其粘贴到第一张纸中的第一个空白行中。因此,当第一个纸上的单元格(这不是我要复制到的纸张(粘贴在第一张纸上时,它们将从A3开始粘贴。随后的每个糊需要在第一个可用的空白行中发生。我可能没有在解释这一点方面做得很好,但会喜欢一些帮助。没有与Win32COM合作。

我也有一个旧脚本中的代码,但是我不明白它是如何复制内容的,这次我如何将其修改为为我工作:

ws.Range(ws.Cells(1,1),ws.Cells(ws.UsedRange.Rows.Count,ws.UsedRange.Columns.Count)).Copy()
wsNew.Paste(wsNew.Cells(wsNew.UsedRange.Rows.Count,1))

如果我很好地了解您的问题,我认为此代码将完成工作:

import win32com.client 
# create an instance of Excel
excel = win32com.client.gencache.EnsureDispatch('Excel.Application')
# Open the workbook
file_name = 'path_to_yourfile.xlsx'
wb = excel.Workbooks.Open(file_name)
# Select the first sheet on which you want to write your data from the other sheets
ws_paste = wb.Sheets('Sheet1')
# Loop over all the sheets
for ws in wb.Sheets:
    if ws.Name != 'Sheet1': # Not the first sheet
        used_range = ws.UsedRange.SpecialCells(11) # 11 = xlCellTypeLastCell from VBA Range.SpecialCells Method
        # With used_range.Row and used_range.Col you get the number of row and col in your range
        # Copy the Range from the cell A2 to the last row/col
        ws.Range("A2", ws.Cells(used_range.Row, used_range.Column)).Copy()
        # Get the last row used in your first sheet
        # NOTE: +1 to go to the next line to not overlapse
        row_copy = ws_paste.UsedRange.SpecialCells(11).Row + 1
        # Paste on the first sheet starting the first empty row and column A(1)
        ws_paste.Paste(ws_paste.Cells(row_copy, 1))
# Save and close the workbook
wb.Save()
wb.Close()
# Quit excel instance
excel.Quit()

我希望它也可以帮助您理解旧代码。

您是否考虑过使用pandas?

import pandas as pd
# create list of panda dataframes for each sheet (data starts ar E6
dfs=[pd.read_excel("source.xlsx",sheet_name=n,skiprows=5,usecols="E:J") for n in range(0,4)]
# concatenate the dataframes
df=pd.concat(dfs)
# write the dataframe to another spreadsheet
writer = pd.ExcelWriter('merged.xlsx')
df.to_excel(writer,'Sheet1')
writer.save()

最新更新