xlwings 및 python을 사용하여 워크시트 복사
xlwings를 Python에서 사용하고 있습니다만, 워크시트를 복사하는 방법을 알 수 없었습니다.특정 워크시트를 템플릿으로 처리하고 수정하기 전에 매번 해당 워크시트를 복사하려고 합니다.
xlwings 버전 0.11.4를 사용하고 있습니다.만약 이 기능이 내장되어 있지 않다면 xlwings 외부에서 pywin32 기능을 사용하여 이 기능을 수행해도 괜찮습니다.
여러 곳을 찾아보고 pywin32 문서를 읽은 후 워크시트를 복사할 수 있는 솔루션을 찾았습니다.
import xlwings as xw
wb = xw.Book('filename.xlsx')
sheet = wb.sheets['Sheet1']
#copy within the same sheet
sheet.api.Copy(Before=sheet.api)
#copy to a new workbook
sheet.api.Copy()
#copy a third time at the beginning of the sheets
sheet2 = wb.sheets['sheet1 (2)']
sheet.api.Copy(Before=sheet2.api)
#copy to an existing workbook by putting it in front of a worksheet object
sheet.api.Copy(Before=existingSheet.api)
이 기능은 xlwings에서 제공하는 네이티브 기능을 벗어나 있습니다.xlwings는 pywin32를 둘러싼 래퍼이기 때문에.api()
call을 사용하면 xlwings에서 문서화되지 않은 pywin32 함수에 액세스할 수 있습니다.
또한 'After' 명령은 워크시트 내에서 작동하지 않습니다. 새 워크북이 열리고 시트가 복사됩니다.필요한 경우 인덱스를 다시 정렬할 수 있기 때문에 큰 문제가 되지 않을 것입니다.
최신 버전의 xlwings에서는 api 대신 simple copy() 함수를 항상 사용할 수 있습니다.Copy() - 다른 워크북 간에 복사하는 경우에도 마찬가지입니다.
# Create two books and add a value to the first sheet of the first book
first_book = xw.Book()
second_book = xw.Book()
first_book.sheets[0]['A1'].value = 'some value'
# Copy to same Book with the default location and name
first_book.sheets[0].copy()
# Copy to same Book with custom sheet name
first_book.sheets[0].copy(name='copied')
# Copy to second Book requires to use before or after
first_book.sheets[0].copy(after=second_book.sheets[0])
이 메뉴얼을 참조해 주세요.
시트를 다른 워크북에 복사하는 방법에 어려움을 겪고 있는 사용자를 위해 다음과 같은 예를 제시하겠습니다.
import xlwings as xw
wb = xw.Book("spravoc" + "/" + "spravoc.xlsx") # file FROM you want to copy sheet
sht = wb.sheets["Dictionary"] #select sheet you want to copy
new_wb = xw.Book("spravoc" + "/" + "spravoc_new.xlsx") # file where you want TO copy
new_wb.sheets.add("Temp", after=1) # add temp sheet, if you want to copy sheet after some other sheet (after=1 - after first sheet)
print(new_wb.sheets)
# copy needed sheet to the new_wb *before* Temp:
sht.api.Copy(Before=new_wb.sheets['Temp'].api)
# now, remove Temp from new_wb
new_wb.sheets['Temp'].delete()
new_wb.save("spravoc" + "/" + "spravoc_new.xlsx")
다른 워크북에 복사할 때 다음을 사용할 수 있습니다.
import xlwings as xw
wb_from = xw.Book(r"test1.xlsx")
wb_to = xw.Book(r"test2.xlsx")
ws_from = wb_from.sheets['Sheet1']
ws_to = wb_to.sheets['Sheet1']
# Copy the sheet BEFORE the sheet of another book.
ws_from.api.Copy(Before=ws_to.api)
# Copy the sheet AFTER the sheet of another book.
ws_from.api.Copy(None, After=ws_to.api)
현재 워크북에 워크시트를 복사하는 경우 xlwings 버전 0.22 이후 기본 제공 버전을 사용할 수도 있습니다.
# Copy the sheet BEFORE ws_from.
sheet.copy(before=ws_from, name="name_of_copied_sheet")
# Copy the sheet AFTER ws_from.
sheet.copy(after=ws_from, name="name_of_copied_sheet")
여러 장을 복사해야 했기 때문에 포기하고 매우 추악한 하이브리드 매크로 방식을 사용했습니다.
'my_macros'라는 '유틸리티' 시트를 만듭니다.xlsm' (Module 1에 다음 매크로 포함)
Sub CopySheetsToAnotherSheet(fromName, toName)
Workbooks(fromName).Sheets(Array("SheetA", "SheetB")).Copy Before:=Workbooks(toName).Sheets(1)
End Sub
그런 다음 소스 및 대상 시트가 열려 있는지 확인하고 다음을 수행합니다.
my_macros = xw.Book('my_macros.xlsm')
a_macro = my_macros.macro('CopySheetsToAnotherSheet')
a_macro('source_sheet.xlsm', 'target_sheet.xlsx')
언급URL : https://stackoverflow.com/questions/45948255/copying-a-worksheet-with-xlwings-and-python
'programing' 카테고리의 다른 글
bash에서 단일 명령을 사용하여 셸 변수에 기본값 할당 (0) | 2023.04.17 |
---|---|
코드 배후에 있는 콜명령어 (0) | 2023.04.17 |
데이터그램 열 가시성 MVVM 바인딩 (0) | 2023.04.17 |
C#에서 Excel 워크북을 만들 때 클래스가 등록되지 않음 오류 발생 (0) | 2023.04.17 |
WPF 명령줄 (0) | 2023.04.17 |