Hướng dẫn how do i open an excel file in python? - làm cách nào để mở tệp excel trong python?

Làm cách nào để mở một tệp là một tệp excel để đọc trong Python?

Tôi đã mở các tệp văn bản, ví dụ, sometextfile.txt với lệnh đọc. Làm cách nào để làm điều đó cho một tệp excel?

hỏi ngày 13 tháng 7 năm 2010 lúc 16:26Jul 13, 2010 at 16:26

1

Chỉnh sửa: Trong phiên bản mới hơn của Pandas, bạn có thể chuyển tên trang tính dưới dạng tham số.
In the newer version of pandas, you can pass the sheet name as a parameter.

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

Kiểm tra các tài liệu để biết ví dụ về cách vượt qua
//pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html

Phiên bản cũ: Bạn cũng có thể sử dụng gói

import pandas as pd
xl = pd.ExcelFile[path + filename]
xl.sheet_names

>>> [u'Sheet1', u'Sheet2', u'Sheet3']

df = xl.parse["Sheet1"]
df.head[]
0 ....
you can use
import pandas as pd
xl = pd.ExcelFile[path + filename]
xl.sheet_names

>>> [u'Sheet1', u'Sheet2', u'Sheet3']

df = xl.parse["Sheet1"]
df.head[]
0 package as well....

Khi bạn đang làm việc với một tệp Excel với nhiều tờ, bạn có thể sử dụng:

import pandas as pd
xl = pd.ExcelFile[path + filename]
xl.sheet_names

>>> [u'Sheet1', u'Sheet2', u'Sheet3']

df = xl.parse["Sheet1"]
df.head[]

import pandas as pd
xl = pd.ExcelFile[path + filename]
xl.sheet_names

>>> [u'Sheet1', u'Sheet2', u'Sheet3']

df = xl.parse["Sheet1"]
df.head[]
1 sẽ in 5 hàng đầu tiên của tệp Excel của bạn

Nếu bạn đang làm việc với một tệp Excel với một tờ, bạn có thể chỉ cần sử dụng:

import pandas as pd
df = pd.read_excel[path + filename]
print df.head[]

Đã trả lời ngày 25 tháng 6 năm 2013 lúc 7:16Jun 25, 2013 at 7:16

2

Hãy thử thư viện XLRD.

[Chỉnh sửa] - Từ những gì tôi có thể thấy từ bình luận của bạn, một cái gì đó giống như đoạn trích bên dưới có thể thực hiện thủ thuật. Tôi giả sử ở đây rằng bạn chỉ đang tìm kiếm một cột cho từ 'John', nhưng bạn có thể thêm nhiều hơn hoặc biến điều này thành một chức năng chung chung hơn. - from what I can see from your comment, something like the snippet below might do the trick. I'm assuming here that you're just searching one column for the word 'john', but you could add more or make this into a more generic function.

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] 

Đã trả lời ngày 13 tháng 7 năm 2010 lúc 16:29Jul 13, 2010 at 16:29

Jon Cagejon lồngJon Cage

35K35 Huy hiệu vàng131 Huy hiệu bạc210 Huy hiệu Đồng35 gold badges131 silver badges210 bronze badges

3

Điều này không đơn giản như mở một tệp văn bản đơn giản và sẽ yêu cầu một số loại mô-đun bên ngoài vì không có gì được tích hợp để làm điều này. Dưới đây là một số tùy chọn:

//www.python-excel.org/

Nếu có thể, bạn có thể muốn xem xét xuất bảng tính Excel dưới dạng tệp CSV và sau đó sử dụng mô-đun Python CSV tích hợp để đọc nó:

//docs.python.org/library/csv.html

Đã trả lời ngày 13 tháng 7 năm 2010 lúc 16:29Jul 13, 2010 at 16:29

Jon Cagejon lồngDonald Miner

35K35 Huy hiệu vàng131 Huy hiệu bạc210 Huy hiệu Đồng8 gold badges90 silver badges117 bronze badges

4

Điều này không đơn giản như mở một tệp văn bản đơn giản và sẽ yêu cầu một số loại mô-đun bên ngoài vì không có gì được tích hợp để làm điều này. Dưới đây là một số tùy chọn:

>>> 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[]

Nếu có thể, bạn có thể muốn xem xét xuất bảng tính Excel dưới dạng tệp CSV và sau đó sử dụng mô-đun Python CSV tích hợp để đọc nó:Jun 22, 2015 at 18:57

Donald Minerdonald Minerwordsforthewise

37.9K8 Huy hiệu vàng90 Huy hiệu bạc117 Huy hiệu đồng5 gold badges81 silver badges111 bronze badges

Có gói OpenPxyl:

Đã trả lời ngày 22 tháng 6 năm 2015 lúc 18:57

wordsforthewiseWordsforthewise

12.4K5 Huy hiệu vàng81 Huy hiệu bạc111 Huy hiệu đồng

###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"]

Điều này có thể giúp:Apr 29, 2018 at 20:03

Apsis0215Apsis0215Apsis0215

Điều này tạo ra một nút lấy danh sách 2D [danh sách các mục danh sách] và đẩy chúng vào bảng tính Excel. Hãy chắc chắn rằng trong [] s có mặt hoặc sẽ ném và ngoại lệ.1 silver badge9 bronze badges

2

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]

Đây là một bản viết lại của nút Dynamo Revit Excel cho Excel 2013 khi nút đóng gói sẵn mặc định tiếp tục phá vỡ. Tôi cũng có một nút đọc tương tự. Cú pháp Excel trong Python rất cảm động.

thnx @codingninja - cập nhật :]Dec 2, 2015 at 18:31

1

Đã trả lời ngày 29 tháng 4 năm 2018 lúc 20:03

import csv
excel = csv.writer[open["file1.csv", "wb"]]

Pikamander2

Phù hiệu 931 Bạc9 Huy hiệu Đồng3 gold badges43 silver badges65 bronze badges

Bây giờ bạn có thể sử dụng sức mạnh của Pandas DataFrames!Nov 3, 2017 at 21:33

1

Python có thể mở các tệp XLS không?

Hàm read_excel của thư viện gấu trúc được sử dụng đọc nội dung của tệp excel vào môi trường Python dưới dạng dữ liệu gấu trúc. Hàm có thể đọc các tệp từ HĐH bằng cách sử dụng đường dẫn thích hợp đến tệp.. The function can read the files from the OS by using proper path to the file.

Bạn có thể mở XLSX trong Python không?

Hai cách phổ biến để đọc các tệp XLSX trong Python là openpyxl và pandas.Phần này sẽ phác thảo các bước bạn có thể thực hiện cho từng bước.OpenPyXL là một thư viện Python được tạo để đọc và viết các tệp Excel 2010 XLSX/XLSM/XLTX/XLTM.Nó có thể đọc cả hai.OpenPyXL and Pandas. This section will outline the steps you can take for each one. OpenPyXL is a Python library created for reading and writing Excel 2010 xlsx/xlsm/xltx/xltm files. It can read both the .

Làm cách nào để tự động mở một tệp excel trong Python?

Để làm việc trên trang tính excel này, chúng tôi sẽ sử dụng thư viện OpenPyXL.Tạo một thư mục trong thư mục của bạn, đặt tên cho nó và cài đặt gói OpenPyXL bằng cách thực thi lệnh sau trong thiết bị đầu cuối của bạn.Bây giờ chúng tôi có thể nhập gói này để làm việc trên bảng tính của chúng tôi.Trước đó, thêm bảng tính trong thư mục dự án của bạn.use a library openpyxl. Create a folder in your directory, give it a name and install the openpyxl package by executing the following command in your terminal. Now we can import this package to work on our spreadsheet. Before that add the spreadsheet in your project folder.

Làm cách nào để đọc một tệp XLSX trong Python?

Làm cách nào để đọc tệp Excel [XLSX] trong Python?Bây giờ, phương thức chung để đọc các tệp XLSX trong Python [với OpenPyXL] là nhập openpyxl [nhập openpyxl] và sau đó đọc sổ làm việc: wb = openpyxl.load_workbook [path_to_excel_file].

Bài Viết Liên Quan

Chủ Đề