developer tip

Python으로 Excel (xls) 파일 읽기 / 파싱

optionbox 2020. 8. 12. 08:08
반응형

Python으로 Excel (xls) 파일 읽기 / 파싱


Python ( CSV 파일 아님)으로 Excel (XLS) 파일을 읽는 가장 좋은 방법은 무엇입니까?

이 작업을 수행하기 위해 Python에서 기본적으로 지원되는 내장 패키지가 있습니까?


파일 을 읽는 데 xlrd적극 권장 .xls합니다.

보이저는 COM 자동화의 사용을 언급했습니다. 몇 년 전에 직접이 작업을 수행 했으므로이 작업을 수행하는 것이 실제 PITA라는 점에 유의하십시오. 주의 사항의 수는 엄청나고 문서는 부족하고 성가시다. 나는 많은 이상한 버그와 문제를 만났는데, 그중 일부는 알아내는 데 많은 시간이 걸렸습니다.

업데이트 : 최신 .xlsx파일의 경우 읽기 및 쓰기에 권장되는 라이브러리는 openpyxl 인 것으로 보입니다 (감사합니다, Ikar Pohorský).


팬더 사용 :

import pandas as pd

xls = pd.ExcelFile("yourfilename.xls")

sheetX = xls.parse(2) #2 is the sheet number

var1 = sheetX['ColumnName']

print(var1[1]) #1 is the row number...

http://www.python-excel.org/ 중 하나를 선택할 수 있습니다
. python xlrd 라이브러리를 권장합니다.

사용하여 설치

pip install xlrd

수입품

import xlrd

통합 문서를 열려면

workbook = xlrd.open_workbook('your_file_name.xlsx')

이름으로 시트 열기

worksheet = workbook.sheet_by_name('Name of the Sheet')

색인별로 시트 열기

worksheet = workbook.sheet_by_index(0)

셀 값 읽기

worksheet.cell(0, 0).value    

팬더가 가장 좋은 방법이라고 생각합니다. 이 하나의 대답은 이미 여기에 사용 팬더와 ExcelFile기능,하지만 나를 위해 제대로 작동하지 않았다. 에서 여기에 내가 발견 read_excel잘 작동 기능 :

import pandas as pd
dfs = pd.read_excel("your_file_name.xlsx", sheet_name="your_sheet_name")
print(dfs.head(10))

PS 기능이 작동 하려면 xlrd설치 해야합니다.read_excel


여기에 나열된 라이브러리 (예 : JExcelApi 또는 xlwt를 기반으로하는 Pyxlreader )와 COM 자동화를 사용 하여 파일을 읽는 데 Excel 자체를 사용할 수 있지만,이를 위해 Office를 소프트웨어 종속성으로 도입하고 있습니다. 항상 옵션이 아닐 수도 있습니다.


(비 파이썬) 프로그램 xls2csv 실행을 고려할 수도 있습니다. xls 파일을 입력하면 csv가 반환됩니다.


xlsx의 경우 https://stackoverflow.com/questions/4371163/reading-xlsx-files-using-python으로 게시 된 솔루션이 마음에 듭니다 . 표준 라이브러리의 모듈 만 사용합니다.

def xlsx(fname):
    import zipfile
    from xml.etree.ElementTree import iterparse
    z = zipfile.ZipFile(fname)
    strings = [el.text for e, el in iterparse(z.open('xl/sharedStrings.xml')) if el.tag.endswith('}t')]
    rows = []
    row = {}
    value = ''
    for e, el in iterparse(z.open('xl/worksheets/sheet1.xml')):
        if el.tag.endswith('}v'):                                
            value = el.text
        if el.tag.endswith('}c'):                                 
            if el.attrib.get('t') == 's':
                value = strings[int(value)]
            letter = el.attrib['r']                             
            while letter[-1].isdigit():
                letter = letter[:-1]
            row[letter] = value
            value = ''
        if el.tag.endswith('}row'):
            rows.append(row)
            row = {}
    return rows

추가 된 개선 사항은 시트 이름별로 콘텐츠를 가져오고 re를 사용하여 열을 가져오고 공유 문자열이 사용되는지 확인하는 것입니다.

def xlsx(fname,sheet):
    import zipfile
    from xml.etree.ElementTree import iterparse
    import re
    z = zipfile.ZipFile(fname)
    if 'xl/sharedStrings.xml' in z.namelist():
        # Get shared strings
        strings = [element.text for event, element
                   in iterparse(z.open('xl/sharedStrings.xml')) 
                   if element.tag.endswith('}t')]
    sheetdict = { element.attrib['name']:element.attrib['sheetId'] for event,element in iterparse(z.open('xl/workbook.xml'))
                                      if element.tag.endswith('}sheet') }
    rows = []
    row = {}
    value = ''

    if sheet in sheets:
    sheetfile = 'xl/worksheets/sheet'+sheets[sheet]+'.xml'
    #print(sheet,sheetfile)
    for event, element in iterparse(z.open(sheetfile)):
        # get value or index to shared strings
        if element.tag.endswith('}v') or element.tag.endswith('}t'):
            value = element.text
        # If value is a shared string, use value as an index
        if element.tag.endswith('}c'):
            if element.attrib.get('t') == 's':
                value = strings[int(value)]
            # split the row/col information so that the row leter(s) can be separate
            letter = re.sub('\d','',element.attrib['r'])
            row[letter] = value
            value = ''
        if element.tag.endswith('}row'):
            rows.append(row)
            row = {}

    return rows

For older Excel files there is the OleFileIO_PL module that can read the OLE structured storage format used.


Python Excelerator handles this task as well. http://ghantoos.org/2007/10/25/python-pyexcelerator-small-howto/

It's also available in Debian and Ubuntu:

 sudo apt-get install python-excelerator

참고URL : https://stackoverflow.com/questions/2942889/reading-parsing-excel-xls-files-with-python

반응형