2017-02-20 1 views
2

대용량의 EXCEL 파일 (예 : 200) 한 통합 문서에서 다른 통합 문서로 특정 워크 시트를 복사하고 싶습니다. 나는 몇 가지 조사를 수행하고 난 한 통합 문서의 워크 시트를 Openpyxl을 사용하여 다른 워크 북으로 복사

이 Openpyxl

으로 그 일을하는 방법을 찾을 수 없습니다 지금까지

def copy_sheet_to_different_EXCEL(path_EXCEL_read,Sheet_name_to_copy,path_EXCEL_Save,Sheet_new_name): 
''' Function used to copy one EXCEL sheet into another file. 

    def path_EXCEL_read,Sheet_name_to_copy,path_EXCEL_Save,Sheet_new_name 


Input data: 
    1.) path_EXCEL_read: the location of the EXCEL file along with the name where the information is going to be saved 
    2.) Sheet_name_to_copy= The name of the EXCEL sheet to copy 
    3.) path_EXCEL_Save: The path of the EXCEL file where the sheet is going to be copied 
    3.) Sheet_new_name: The name of the new EXCEL sheet 

Output data: 
    1.) Status= If 0, everything went OK. If 1, one error occurred. 

Version History: 
1.0 (2017-02-20): Initial version. 

''' 

status=0 

if(path_EXCEL_read.endswith('.xls')==1): 
    print('ERROR - EXCEL xls file format is not supported by openpyxl. Please, convert the file to an XLSX format') 
    status=1 
    return status 

try: 
    wb = openpyxl.load_workbook(path_EXCEL_read,read_only=True) 
except: 
    print('ERROR - EXCEL file does not exist in the following location:\n {0}'.format(path_EXCEL_read)) 
    status=1 
    return status 


Sheet_names=wb.get_sheet_names() # We copare against the sheet name we would like to cpy 

if ((Sheet_name_to_copy in Sheet_names)==0): 
    print('ERROR - EXCEL sheet does not exist'.format(Sheet_name_to_copy)) 
    status=1 
    return status 

# We checking if the destination file exists 


if (os.path.exists(path_EXCEL_Save)==1): 
    #If true, file exist so we open it 

    if(path_EXCEL_Save.endswith('.xls')==1): 
     print('ERROR - Destination EXCEL xls file format is not supported by openpyxl. Please, convert the file to an XLSX format') 
     status=1 
    return status 

    try: 
     wdestiny = openpyxl.load_workbook(path_EXCEL_Save) 
    except: 
     print('ERROR - Destination EXCEL file does not exist in the following location:\n {0}'.format(path_EXCEL_read)) 
     status=1 
    return status 

    #we check if the destination sheet exists. If so, we will delete it 

    destination_list_sheets = wdestiny.get_sheet_names() 

    if((Sheet_new_name in destination_list_sheets) ==True): 
     print('WARNING - Sheet "{0}" exists in: {1}. It will be deleted!'.format(Sheet_new_name,path_EXCEL_Save)) 
     wdestiny.remove_sheet(Sheet_new_name) 

else: 
    wdestiny=openpyxl.Workbook() 
# We copy the Excel sheet 

try: 
    sheet_to_copy = wb.get_sheet_by_name(Sheet_name_to_copy) 
    target = wdestiny.copy_worksheet(sheet_to_copy) 
    target.title=Sheet_new_name 
except: 
    print('ERROR - Could not copy the EXCEL sheet. Check the file') 
    status=1 
    return status 

try: 
    wdestiny.save(path_EXCEL_Save) 
except: 
    print('ERROR - Could not save the EXCEL sheet. Check the file permissions') 
    status=1 
    return status 

#Program finishes 
return status  

어떤 제안을 코드 개발한다? 이 통합 문서에 따라서 다릅니다 전역 상수에 의존하기 때문에

건배

답변

2

당신은 통합 문서 사이에 복사 할 copy_worksheet()을 사용할 수 없습니다. 유일하게 안전하고 신뢰할 수있는 방법은 행 단위 및 셀 단위로 이동하는 것입니다.

당신은 내가 하나의 통합 문서에 여러 통합 문서에서 데이터를 대조하는 비슷한 요구를했다 discussions about this feature

1

을 읽을 수 있습니다. openpyxl에는 inbuilt 메소드가 없습니다.

나는 저를 대신하여 아래 스크립트를 만들었습니다.

참고 : 모든 용도의 책에는 동일한 형식의 데이터가 포함되어 있습니다.

from openpyxl import load_workbook 
import os 


# The below method is used to read data from an active worksheet and store it in memory. 
def reader(file): 
    global path 
    abs_file = os.path.join(path, file) 
    wb_sheet = load_workbook(abs_file).active 
    rows = [] 
    # min_row is set to 2, to ignore the first row which contains the headers 
    for row in wb_sheet.iter_rows(min_row=2): 
     row_data = [] 
     for cell in row: 
      row_data.append(cell.value) 
     # custom column data I am adding, not needed for typical use cases 
     row_data.append(file[17:-6]) 
     # Creating a list of lists, where each list contain a typical row's data 
     rows.append(row_data) 
    return rows 


if __name__ == '__main__': 
    # Folder in which my source excel sheets are present 
    path = r'C:\Users\tom\Desktop\Qt' 
    # To get the list of excel files 
    files = os.listdir(path) 
    for file in files: 
     rows = reader(file) 
     # below mentioned file name should be already created 
     book = load_workbook('new.xlsx') 
     sheet = book.active 
     for row in rows: 
      sheet.append(row) 
     book.save('new.xlsx') 
1

방금이 질문을 발견했습니다. 언급 된 바와 같이 here과 같은 좋은 해결 방법은 메모리에있는 원래 wb을 수정하여 다른 이름으로 저장할 수 있습니다. 예 :

import openpyxl 

# your starting wb with 2 Sheets: Sheet1 and Sheet2 
wb = openpyxl.load_workbook('old.xlsx') 

sheets = wb.sheetnames # ['Sheet1', 'Sheet2'] 

for s in sheets: 

    if s != 'Sheet2': 
     sheet_name = wb.get_sheet_by_name(s) 
     wb.remove_sheet(sheet_name) 

# your final wb with just Sheet1 
wb.save('new.xlsx') 
관련 문제