簡體   English   中英

使用python讀取excel表時出錯

[英]Getting error while reading excel sheet using python

from xlrd import *

book = open_workbook("File_1.xls")

#sheet = book.sheets()[0]           
#book.sheets() returns a list of sheet objects...     alternatively...
#sheet = book.sheet_by_name("qqqq") #we can pull by name
 sheet = book.sheet_by_index(0)     #or by the index it has in excel's sheet collection

r = sheet.row(0)                    #returns all the CELLS of row 0,
c = sheet.col_values(0)             #returns all the VALUES of row 0,

for i in xrange(sheet.nrows):
print sheet.row_values(5) 

我正在讀取我桌面上的文件,但是當我運行用python編寫的腳本時,它給出了錯誤

  Traceback (most recent call last):
  File "C:\Python26\ReadXLS.py", line 6, in <module>
  book = open_workbook("File_1.xls")
  File "C:\Python26\Lib\site-packages\xlrd\__init__.py", line 449, in open_workbook
  ragged_rows=ragged_rows,
 File "C:\Python26\Lib\site-packages\xlrd\__init__.py", line 941, in biff2_8_load
 f = open(filename, open_mode)
  IOError: [Errno 2] No such file or directory: 'File_1.xls'

您需要在運行Python之前使用cd Desktop ,因為您的錯誤消息顯示該文件不存在:

No such file or directory: 'File_1.xls'

另一個修復方法是將Python文件移動到與Excel文件相同的文件夾中。

驗證腳本和文件是否在目錄中,或指定excel文件的絕對路徑。

另請注意,如果您嘗試相對打開文件,則將使用初始化python解釋器的當前工作目錄來完成此操作。

如果您需要使用較新的xlsx格式,我還建議使用openpyxl http://packages.python.org/openpyxl/

如果有的話,您將面臨路徑問題,請嘗試在程序中查找當前路徑

>>> import os.path
>>> import os
>>> os.curdir
'.'
>>> os.path.abspath(os.curdir)
'/Users/xxxx/temp'
>>> 

這就是它在Unix上的表現。 它將在Windows上顯示不同。

這樣您就會知道,如果這是您當前文件的放置位置。

碼:

from xlrd import *
import os.path
import os
print os.path.abspath(os.curdir)

book = open_workbook("File_1.xls")
#sheet = book.sheets()[0]           
#book.sheets() returns a list of sheet objects...     alternatively...
#sheet = book.sheet_by_name("qqqq") #we can pull by name
 sheet = book.sheet_by_index(0)     #or by the index it has in excel's sheet collection

r = sheet.row(0)                    #returns all the CELLS of row 0,
c = sheet.col_values(0)             #returns all the VALUES of row 0,

for i in xrange(sheet.nrows):
print sheet.row_values(5) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM