Python에서 Excel 파일을 열려면 어떻게 해야 하나요?
Python에서 읽기 위해 Excel 파일인 파일을 열려면 어떻게 해야 하나요?
예를 들어 텍스트 파일을 열어봤는데sometextfile.txt
읽기 명령을 사용합니다.엑셀 파일에 대해 어떻게 해야 하나요?
편집:
최신 버전의 판다에서는 시트 이름을 매개 변수로 전달할 수 있습니다.
file_name = # path to file + file name
sheet = # sheet name or sheet number or list of sheet numbers and names
import pandas as pd
df = pd.read_excel(io=file_name, sheet_name=sheet)
print(df.head(5)) # print first 5 rows of the dataframe
합격 방법에 대한 예는 문서를 참조하십시오.sheet_name
:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html
이전 버전:
패키지를 사용할 수도 있습니다.
여러 시트로 구성된 Excel 파일을 사용하는 경우 다음을 사용할 수 있습니다.
import pandas as pd
xl = pd.ExcelFile(path + filename)
xl.sheet_names
>>> [u'Sheet1', u'Sheet2', u'Sheet3']
df = xl.parse("Sheet1")
df.head()
df.head()
Excel 파일의 첫 번째 5 행을 인쇄합니다.
단일 시트로 Excel 파일을 작업하는 경우 다음과 같이 간단히 사용할 수 있습니다.
import pandas as pd
df = pd.read_excel(path + filename)
print df.head()
[편집] - 당신의 코멘트에서 알 수 있듯이, 아래의 토막 같은 것이 도움이 될 것 같습니다.여기서 'john'이라는 단어를 검색한다고 가정합니다만, 더 추가하거나 더 일반적인 함수로 만들 수 있습니다.
from xlrd import open_workbook
book = open_workbook('simple.xls',on_demand=True)
for name in book.sheet_names():
if name.endswith('2'):
sheet = book.sheet_by_name(name)
# Attempt to find a matching row (search the first column for 'john')
rowIndex = -1
for cell in sheet.col(0): #
if 'john' in cell.value:
break
# If we found the row, print it
if row != -1:
cells = sheet.row(row)
for cell in cells:
print cell.value
book.unload_sheet(name)
이것은 일반 텍스트 파일을 여는 것만큼 간단하지 않으며, 이를 위해 내장된 것이 없기 때문에 일종의 외부 모듈이 필요합니다.몇 가지 옵션은 다음과 같습니다.
가능하면 Excel 스프레드시트를 CSV 파일로 내보낸 후 내장된 python csv 모듈을 사용하여 읽어보는 것을 고려해 보십시오.
http://docs.python.org/library/csv.html
openpxy 패키지가 있습니다.
>>> from openpyxl import load_workbook
>>> wb2 = load_workbook('test.xlsx')
>>> print wb2.get_sheet_names()
['Sheet2', 'New Title', 'Sheet1']
>>> worksheet1 = wb2['Sheet1'] # one way to load a worksheet
>>> worksheet2 = wb2.get_sheet_by_name('Sheet2') # another way to load a worksheet
>>> print(worksheet1['D18'].value)
3
>>> for row in worksheet1.iter_rows():
>>> print row[0].value()
xlrd만 필요한 xlpython 패키지를 사용할 수 있습니다.https://pypi.python.org/pypi/xlpython 및 매뉴얼은 이쪽 https://github.com/morfat/xlpython 에서 확인하실 수 있습니다.
다음과 같은 이점이 있습니다.
그러면 2D 목록(목록 항목 목록)을 가져와서 Excel 스프레드시트에 푸시하는 노드가 생성됩니다. IN[]이 존재하는지, 존재하는지, 또는 예외가 발생하는지 확인합니다.
Excel 2013용 Revit Excel dynamo 노드를 다시 쓴 것입니다. 기본 사전 패키지 노드가 계속 손상되었습니다.비슷한 읽기 노드도 있습니다.Python의 Excel 구문은 까다롭다.
thnx @CodingNinja - 갱신 : )
###Export Excel - intended to replace malfunctioning excel node
import clr
clr.AddReferenceByName('Microsoft.Office.Interop.Excel, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c')
##AddReferenceGUID("{00020813-0000-0000-C000-000000000046}") ''Excel C:\Program Files\Microsoft Office\Office15\EXCEL.EXE
##Need to Verify interop for version 2015 is 15 and node attachemnt for it.
from Microsoft.Office.Interop import * ##Excel
################################Initialize FP and Sheet ID
##Same functionality as the excel node
strFileName = IN[0] ##Filename
sheetName = IN[1] ##Sheet
RowOffset= IN[2] ##RowOffset
ColOffset= IN[3] ##COL OFfset
Data=IN[4] ##Data
Overwrite=IN[5] ##Check for auto-overwtite
XLVisible = False #IN[6] ##XL Visible for operation or not?
RowOffset=0
if IN[2]>0:
RowOffset=IN[2] ##RowOffset
ColOffset=0
if IN[3]>0:
ColOffset=IN[3] ##COL OFfset
if IN[6]<>False:
XLVisible = True #IN[6] ##XL Visible for operation or not?
################################Initialize FP and Sheet ID
xlCellTypeLastCell = 11 #####define special sells value constant
################################
xls = Excel.ApplicationClass() ####Connect with application
xls.Visible = XLVisible ##VISIBLE YES/NO
xls.DisplayAlerts = False ### ALerts
import os.path
if os.path.isfile(strFileName):
wb = xls.Workbooks.Open(strFileName, False) ####Open the file
else:
wb = xls.Workbooks.add# ####Open the file
wb.SaveAs(strFileName)
wb.application.visible = XLVisible ####Show Excel
try:
ws = wb.Worksheets(sheetName) ####Get the sheet in the WB base
except:
ws = wb.sheets.add() ####If it doesn't exist- add it. use () for object method
ws.Name = sheetName
#################################
#lastRow for iterating rows
lastRow=ws.UsedRange.SpecialCells(xlCellTypeLastCell).Row
#lastCol for iterating columns
lastCol=ws.UsedRange.SpecialCells(xlCellTypeLastCell).Column
#######################################################################
out=[] ###MESSAGE GATHERING
c=0
r=0
val=""
if Overwrite == False : ####Look ahead for non-empty cells to throw error
for r, row in enumerate(Data): ####BASE 0## EACH ROW OF DATA ENUMERATED in the 2D array #range( RowOffset, lastRow + RowOffset):
for c, col in enumerate (row): ####BASE 0## Each colmn in each row is a cell with data ### in range(ColOffset, lastCol + ColOffset):
if col.Value2 >"" :
OUT= "ERROR- Cannot overwrite"
raise ValueError("ERROR- Cannot overwrite")
##out.append(Data[0]) ##append mesage for error
############################################################################
for r, row in enumerate(Data): ####BASE 0## EACH ROW OF DATA ENUMERATED in the 2D array #range( RowOffset, lastRow + RowOffset):
for c, col in enumerate (row): ####BASE 0## Each colmn in each row is a cell with data ### in range(ColOffset, lastCol + ColOffset):
ws.Cells[r+1+RowOffset,c+1+ColOffset].Value2 = col.__str__()
##run macro disbled for debugging excel macro
##xls.Application.Run("Align_data_and_Highlight_Issues")
import pandas as pd
import os
files = os.listdir('path/to/files/directory/')
desiredFile = files[i]
filePath = 'path/to/files/directory/%s'
Ofile = filePath % desiredFile
xls_import = pd.read_csv(Ofile)
이제 Panda DataFrames의 강력한 기능을 사용할 수 있습니다!
이 코드는 Python 3.5.2에서 작동했습니다.열리고 저장되며 탁월합니다.현재 파일에 데이터를 저장하는 방법을 연구하고 있습니다만, 코드는 다음과 같습니다.
import csv
excel = csv.writer(open("file1.csv", "wb"))
언급URL : https://stackoverflow.com/questions/3239207/how-can-i-open-an-excel-file-in-python
'programing' 카테고리의 다른 글
libc++abi.dylib: NSException 유형(lldb)을 제외하고 수집되지 않은 종료 (0) | 2023.04.16 |
---|---|
파일에 있는 모든 숫자를 빠르게 합산하려면 어떻게 해야 합니까? (0) | 2023.04.16 |
git 저장소의 줄 수 (0) | 2023.04.16 |
String에서 곱슬곱슬한 대괄호 '{'를 이스케이프합니다.포맷 (0) | 2023.04.16 |
WPF 익스팬더 헤더의 스타일링 방법 (0) | 2023.04.16 |