프로그래밍/파이썬

파이썬 엑셀 파일 읽기

에이티에스 2023. 7. 4. 23:43
728x90

Excel은 Microsoft에서 개발한 Windows용 스프레드시트 응용 프로그램입니다. Excel은 데이터를 표 형식으로 저장합니다. 데이터를 분석하고 유지 관리하기 위한 손쉬운 액세스를 제공합니다. 다양한 소프트웨어 분야에서 널리 사용됩니다.

Excel 스프레드시트 문서는 확장명이 .xlsx인 파일에 저장됩니다. 스프레드시트의 첫 번째 행은 일반적으로 헤더용으로 예약되고 첫 번째 열은 샘플링 단위를 식별합니다.

특정 열과 행에 있는 상자를 셀이라고 하며, 각 셀에는 숫자 또는 텍스트 값이 포함될 수 있습니다. 데이터가 있는 셀의 그리드가 시트를 형성합니다.

 

Excel 파일에서 읽기

Python은 Excel 파일을 읽고, 쓰고, 수정할 수 있는 기능을 제공합니다. xlrd 모듈은 excel 파일 작업에 사용됩니다. Python은 xlrd 모듈과 함께 제공되지 않습니다. 먼저 다음 명령을 사용하여 이 모듈을 설치해야 합니다:

pip install xlrd

통합 문서 만들기:

워크북에는 Excel 파일의 모든 데이터가 저장됩니다. 다음 입력(excel) 파일을 고려해 보겠습니다.

 

다음과 같은 코드를 생각해 볼 수 있습니다.

import xlrd
# Give the location of the file
loc = ("location of file")
 # To open a Workbook
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0) 
 #for row 0 and column 0
sheet.cell_value(0, 0) 

위의 예에서는 먼저 xlrd 모듈을 가져오고 파일의 위치를 보유하는 loc 변수를 선언했습니다. 그런 다음 엑셀 파일에서 작업 워크북을 열었습니다.

 

  • 열과 행의 수를 추출합니다
import xlrd
loc = ("location of file")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0,0)
print("The number of column:",sheet.ncols)
print("The number of rows:",sheet.nrows)

출력:

The number of column: 3
The number of rows: 7
  • 모든 열 이름 추출
import xlrd
loc = ("location of file")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
# For row 0 and column 0
sheet.cell_value(0, 0)
for i in range(sheet.ncols):
    print(sheet.cell_value(0, i))

출력:

Roll No.
Name
Year 
  • 특정 행 값 추출
import xlrd
# loc = ("location of file")
loc = ("location of file")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
# For row 0 and column 0
sheet.cell_value(0, 0)
print(sheet.row_values(1)) #It will return an list containing the row value
print(sheet.row_values(2)) #It will return an list containing the row value

출력:

[90017.0, 'Himanshu Dubey', 1.0]
[90018.0, 'Sachin Tiwari', 1.0] 

 

판다에서 읽기

Pandas는 NumPy 라이브러리의 맨 위에 구축된 오픈 소스 Python 라이브러리입니다. 먼저 판다 모듈을 수입해야 합니다. URL에서 xls 및 xlsx 확장을 모두 지원합니다. 다음 예를 생각해 보십시오:

 

import pandas as pd
#Using read_excel function to read file
df = pd.read_excel('location of file')
print(df) 

출력:

 Roll No. Name Year
 0 90017 Himanshu Dubey 1
 1 90018 Sachin Tiwari  1
 2 90019 Krishna Shukla 1
 3 80014 Prince Sharma  2
 4 80015 Anubhav Panday 2
 5 80013 Aradhya        3  
  • 정확한 행 이름
import pandas as pd
#Using read_excel function to read file
df = pd.read_excel('location of file')
print(df.columns) 

출력

(['Roll No.', 'Name', 'Year'], dtype='object')

 

Python은 읽기, 쓰기, 산술 연산 등 Excel 파일에서 여러 연산을 수행할 수 있는 openpyxl을 제공합니다. 명령줄에서 pip을 사용하여 openpyxl을 설치해야 합니다.

import openpyxl
wb = openpyxl.Workbook()
sheet = wb.active
sheet_title = sheet.title
print("My sheet title: " + sheet_title)

출력:

My sheet title: Sheet
728x90
반응형
그리드형

'프로그래밍 > 파이썬' 카테고리의 다른 글

서킷파이썬 설치방법  (0) 2023.10.10
서킷파이썬(CircuitPython)이란  (0) 2023.10.10
파이썬 CSV 파일 읽기  (0) 2023.06.28
파이썬 Python for else 문  (0) 2023.06.23
파이썬 Python For else  (0) 2023.06.22