
오늘날 기술 발전의 시대에 데이터 과학자, 분석가 및 자동화 엔지니어를 포함한 많은 전문가들이 Excel(XLS, XLSX) 일상 활동에서 형식적으로 다루는 파일. 실제로 Python 라이브러리는 작업을 자동화하고 데이터 조작을 실행하는 좋은 방법을 제공하므로 Excel 파일을 수동으로 조작하는 힘든 프로세스를 피할 수 있습니다. 이 글은 파이썬을 이용한 엑셀 조작을 인지하는 방법을 제공할 것이며, 이제 **파이썬 엑셀 라이브러리*를 이용하여 파이썬에서 엑셀 파일을 만들고 읽는 방법에 대해 알아보자. 또한 Python을 사용하여 Excel 파일에 데이터, 피벗 테이블 및 차트를 삽입하는 방법을 설명합니다.
이 문서에서는 다음 사항을 다룹니다.
- Python Excel 라이브러리 설치
- Python에서 Excel 파일 읽기
- Python에서 Excel 파일 만들기
- Python을 사용하여 Excel 시트에 쓰기
- Python에서 Excel 시트로 차트 만들기
- Python을 사용하여 Excel에서 피벗 테이블 추가
Python Excel 라이브러리 - 설치
Python에서 Excel(XLS, XLSX) 파일을 만들고 읽기 위해 Aspose.Cells for Python via Java를 사용합니다. 이 Python Excel 라이브러리의 효능은 데이터 추출, 데이터 조작, 심지어 처음부터 Excel 파일 생성과 같은 Excel 파일과 관련된 많은 작업을 처리할 수 있는 능력에서 나타납니다.
아래 제공된 pip 명령을 사용하여 PyPI에서 패키지를 다운로드하거나 설치하십시오.
pip install aspose-cells
파이썬에서 엑셀 파일 읽기
아시다시피 Excel 통합 문서는 하나 이상의 워크시트로 구성되며 각 워크시트는 행 및 열 인덱스로 식별되는 셀 그리드로 구성됩니다. Python에서 Excel 파일 읽기에 사용할 수 있는 패키지가 많이 있지만 이 섹션에서는 Aspose Python Excel 라이브러리를 사용합니다.
다음은 Python에서 XLSX를 읽는 단계입니다.
- 먼저 Workbook 클래스를 사용하여 Excel 파일을 로드합니다.
- 그런 다음 Workbook.getWorksheets() 메서드를 사용하여 WorksheetCollection에 대한 참조를 가져옵니다.
- 마지막으로 컬렉션의 워크시트를 반복하고 각 워크시트에 대해 해당 행과 열을 반복하여 셀 값에 액세스하고 인쇄합니다.
다음 코드 샘플은 Python을 사용하여 Excel 파일을 읽는 방법을 보여줍니다.
# Load Excel workbook | |
wb = Workbook("workbook.xlsx") | |
# Get worksheets collection | |
collection = wb.getWorksheets() | |
collectionCount = collection.getCount() | |
# Loop through all the worksheets | |
for worksheetIndex in range(collectionCount): | |
# Get worksheet using its index | |
worksheet = collection.get(worksheetIndex) | |
# Print worksheet name | |
print("Worksheet: " + str(worksheet.getName())) | |
# Get number of rows and columns | |
rows = worksheet.getCells().getMaxDataRow() | |
cols = worksheet.getCells().getMaxDataColumn() | |
# Loop through rows | |
for i in range(rows): | |
# Loop through each column in selected row | |
for j in range(cols): | |
# Print cell value | |
print(worksheet.getCells().get(i, j).getValue(), end =" | ") | |
# Print line break | |
print("\n") |
원하는 워크시트의 참조를 얻으려면 Workbook.getWorksheets().get(index) 메서드를 사용할 수 있습니다. 다음 코드 샘플은 이러한 경우를 보여줍니다.
# Load Excel workbook | |
wb = Workbook("workbook.xlsx") | |
# Get worksheets collection | |
worksheet = wb.getWorksheets().get(0) | |
# Print worksheet name | |
print("Worksheet: " + str(worksheet.getName())) | |
# Get number of rows and columns | |
rows = worksheet.getCells().getMaxDataRow() | |
cols = worksheet.getCells().getMaxDataColumn() | |
# Loop through rows | |
for i in range(rows): | |
# Loop through each column in selected row | |
for j in range(cols): | |
# print cell value | |
print(worksheet.getCells().get(i, j).getValue(), end =" | ") | |
# Print line break | |
print("\n") |
파이썬은 엑셀 파일을 생성
이 섹션에서는 Python에서 Excel 파일을 만드는 방법을 배웁니다.
다음은 Python에서 Excel 파일을 만드는 단계입니다.
- 먼저 Workbook 클래스의 새 개체를 만듭니다.
- 둘째, Workbook.getWorksheets().get(index) 메서드를 사용하여 원하는 Worksheet의 참조를 가져옵니다.
- 그런 다음 Worksheet.getCells().get().putValue() 메서드를 사용하여 원하는 셀에 값을 삽입합니다.
- 마지막으로 Workbook.Save 메서드를 사용하여 통합 문서를 저장합니다.
다음 코드 샘플은 Python을 사용하여 Excel 파일을 만드는 방법을 보여줍니다.
# create a new XLSX workbook | |
wb = Workbook(FileFormatType.XLSX) | |
# insert value in the cells | |
wb.getWorksheets().get(0).getCells().get("A1").putValue("Hello World!") | |
# save workbook as .xlsx file | |
wb.save("workbook.xlsx") |
다음과 같이 출력이 표시됩니다.

Python Excel에 데이터 쓰기
지금까지 Python Excel 라이브러리를 사용하여 Python에서 Excel 파일을 만들고 읽는 방법을 배웠습니다. 이제 강력한 Excel용 Python 패키지의 다른 중요한 기능을 배울 시간입니다. 일부 데이터를 Excel 파일에 작성해 보겠습니다. 이전 섹션에서 설명한 대로 Excel 파일을 만들거나 로드할 수 있습니다. 시트의 셀 위치를 인식하면 Worksheet.getCells().get().putValue() 메서드를 사용하여 Excel 파일에 데이터를 쉽게 쓸 수 있습니다.
Excel 파일에 데이터를 쓰는 Python 코드는 다음과 같습니다.
# create a new XLSX workbook | |
wb = Workbook("workbook.xlsx") | |
# insert value in the cells | |
wb.getWorksheets().get(0).getCells().get("A1").putValue("Location") | |
wb.getWorksheets().get(0).getCells().get("B1").putValue("Person") | |
wb.getWorksheets().get(0).getCells().get("A2").putValue("Home") | |
wb.getWorksheets().get(0).getCells().get("B2").putValue("abc") | |
wb.getWorksheets().get(0).getCells().get("A3").putValue("Office") | |
wb.getWorksheets().get(0).getCells().get("B3").putValue("xyz") | |
# save workbook as .xlsx file | |
wb.save("workbook-updated.xlsx") |
출력은 다음과 같이 표시됩니다.

Python Excel 시트에서 차트 만들기
Excel에서 차트를 만들 때 기본적으로 데이터 내에 존재하는 복잡한 연결, 진행 및 뉘앙스를 효과적으로 표현할 수 있는 데이터의 시각적 그림을 생성합니다. Python Excel 라이브러리는 막대 차트에서 세로 막대형 차트, 선형 차트에서 분산형 차트, 원형 차트에서 사용자의 특정 요구 사항 및 기본 설정에 맞게 조정할 수 있는 기타 그래프 대안에 이르기까지 다양한 차트 유형을 제공합니다. Excel 시트에서 차트를 만드는 방법에 대해 알아보겠습니다.
Python에서 Excel 파일로 차트를 만드는 단계는 다음과 같습니다.
- Workbook 클래스를 사용하여 Excel 파일을 생성하거나 불러옵니다.
- 원하는 워크시트의 셀에 값을 추가합니다.
- Worksheet.getCharts() 메서드를 사용하여 차트 컬렉션을 가져옵니다.
- Worksheet.getCharts().add(type, upperLeftRow, upperLeftColumn, lowerRightRow, lowerRightColumn) 메서드를 사용하여 차트 컬렉션에 새 차트를 추가합니다.
- 차트에 대해 NSeries를 지정합니다.
- Workbook.save(fileName) 메서드를 사용하여 Excel 파일을 저장합니다.
다음 코드는 Python을 사용하여 Excel 시트에 차트를 만드는 방법을 보여줍니다.
# create a new XLSX workbook | |
workbook = Workbook(FileFormatType.XLSX) | |
# obtaining the reference of the first worksheet | |
worksheets = workbook.getWorksheets() | |
sheet = worksheets.get(0) | |
# adding some sample value to cells | |
cells = sheet.getCells() | |
cell = cells.get("A1") | |
cell.setValue(50) | |
cell = cells.get("A2") | |
cell.setValue(100) | |
cell = cells.get("A3") | |
cell.setValue(150) | |
cell = cells.get("B1") | |
cell.setValue(4) | |
cell = cells.get("B2") | |
cell.setValue(20) | |
cell = cells.get("B3") | |
cell.setValue(50) | |
# get charts in worksheet | |
charts = sheet.getCharts() | |
# adding a chart to the worksheet | |
chartIndex = charts.add(ChartType.PYRAMID, 5, 0, 15, 5) | |
chart = charts.get(chartIndex) | |
# adding NSeries (chart data source) to the chart ranging from "A1" | |
# cell to "B3" | |
serieses = chart.getNSeries() | |
serieses.add("A1:B3", True) | |
# write the Excel file | |
workbook.save("workbook_with_chart.xlsx") |
다음 스크린샷은 위 코드의 출력을 보여줍니다.

Python Excel 피벗 테이블: Python을 사용하여 Excel에서 피벗 테이블을 만드는 방법
Excel의 피벗 테이블을 사용하면 방대한 양의 데이터를 빠르고 능숙하게 검토할 수 있습니다. 또한 데이터를 시각적으로 매력적일 뿐만 아니라 데이터 내의 숨겨진 추세, 식별하기 어려운 패턴 및 복잡한 관계를 발굴하는 데 매우 효율적인 매끄럽고 능률적인 형식으로 데이터를 신중하게 구성하고 요약합니다. 이 섹션에서는 Python을 사용하여 Excel에서 피벗 테이블을 만드는 방법을 배웁니다.
Python에서 Excel의 피벗 테이블을 삽입하는 단계는 다음과 같습니다.
- 처음에 Workbook 클래스를 사용하여 새 Excel 파일을 로드하거나 생성합니다.
- 그런 다음 워크시트에 원하는 데이터를 추가합니다.
- 그런 다음 Worksheet.getPivotTables().add(sourceData, destCellName, tableName) 메서드를 사용하여 새 피벗 테이블을 삽입합니다.
- 그런 다음 피벗 테이블의 행, 열 및 데이터 영역을 지정하십시오.
- 마지막으로 통합 문서를 저장합니다.
다음 코드는 Python을 사용하여 Excel 시트에 피벗 테이블을 만드는 방법을 보여줍니다.
# create a new XLSX workbook | |
workbook = Workbook(FileFormatType.XLSX) | |
# obtaining the reference of the newly added worksheet | |
sheetIndex = workbook.getWorksheets().add() | |
sheet = workbook.getWorksheets().get(sheetIndex) | |
cells = sheet.getCells() | |
# setting the value to the cells | |
cell = cells.get("A1") | |
cell.setValue("Sport") | |
cell = cells.get("B1") | |
cell.setValue("Quarter") | |
cell = cells.get("C1") | |
cell.setValue("Sales") | |
cell = cells.get("A2") | |
cell.setValue("Golf") | |
cell = cells.get("A3") | |
cell.setValue("Golf") | |
cell = cells.get("A4") | |
cell.setValue("Tennis") | |
cell = cells.get("A5") | |
cell.setValue("Tennis") | |
cell = cells.get("A6") | |
cell.setValue("Tennis") | |
cell = cells.get("A7") | |
cell.setValue("Tennis") | |
cell = cells.get("A8") | |
cell.setValue("Golf") | |
cell = cells.get("B2") | |
cell.setValue("Qtr3") | |
cell = cells.get("B3") | |
cell.setValue("Qtr4") | |
cell = cells.get("B4") | |
cell.setValue("Qtr3") | |
cell = cells.get("B5") | |
cell.setValue("Qtr4") | |
cell = cells.get("B6") | |
cell.setValue("Qtr3") | |
cell = cells.get("B7") | |
cell.setValue("Qtr4") | |
cell = cells.get("B8") | |
cell.setValue("Qtr3") | |
cell = cells.get("C2") | |
cell.setValue(1500) | |
cell = cells.get("C3") | |
cell.setValue(2000) | |
cell = cells.get("C4") | |
cell.setValue(600) | |
cell = cells.get("C5") | |
cell.setValue(1500) | |
cell = cells.get("C6") | |
cell.setValue(4070) | |
cell = cells.get("C7") | |
cell.setValue(5000) | |
cell = cells.get("C8") | |
cell.setValue(6430) | |
pivotTables = sheet.getPivotTables() | |
# adding a PivotTable to the worksheet | |
index = pivotTables.add("=A1:C8", "E3", "PivotTable1") | |
# accessing the instance of the newly added PivotTable | |
pivotTable = pivotTables.get(index) | |
# unshowing grand totals for rows. | |
pivotTable.setRowGrand(False) | |
# dragging the first field to the row area. | |
pivotTable.addFieldToArea(PivotFieldType.ROW, 0) | |
# dragging the second field to the column area. | |
pivotTable.addFieldToArea(PivotFieldType.COLUMN, 1) | |
# dragging the third field to the data area. | |
pivotTable.addFieldToArea(PivotFieldType.DATA, 2) | |
# write the Excel file | |
workbook.save("workbook_with_pivot_table.xlsx") |
다음 이미지는 위 코드의 출력을 표시합니다.

무료 라이선스 받기
무료 임시 라이선스를 다운로드하여 평가 제한 없이 API를 테스트할 수 있습니다.
합산
요약하면 Python에서 Excel 파일을 만들고 읽는 방법을 배웠기를 바랍니다. 두 가지 경우를 모두 간략하게 설명했습니다. 또한 강력한 Python Excel 조작 라이브러리를 사용하여 Excel에서 피벗 테이블, 차트 및 간단한 데이터를 추가하는 방법을 살펴보았습니다.
Python Excel 라이브러리에 대해 자세히 알아보려면 문서를 방문하십시오.
마지막으로 정기적인 업데이트를 위해 conholdate.com을 계속 방문하십시오.
질문하기
포럼에 질문이나 의견을 게시할 수 있습니다.