本文转自:https://blog.csdn.net/fengbingyang/article/details/17080103
http://www.python-excel.org/这个网站罗列了很多关于在Python下操作Excel文件的信息,这里选择了其介绍的第一个模块xlrd 。
xlrd 0.9.2版本跨平台同时支持.xls和.xlsx后缀的Excel,非常适合用来处理Excel数据。
1.首先问题是在windos10下面创建excel的表格,直接用python读取会报错。错误如下:
Traceback (most recent call last):
File "C:/Users/shengxin/.PyCharmCE2018.3/config/scratches/test.py", line 6, in <module>
data = pd.read_csv(file)
File "F:\ProgramData\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 709, in parser_f
return _read(filepath_or_buffer, kwds)
File "F:\ProgramData\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 449, in _read
parser = TextFileReader(filepath_or_buffer, **kwds)
File "F:\ProgramData\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 818, in __init__
self._make_engine(self.engine)
File "F:\ProgramData\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 1049, in _make_engine
self._engine = CParserWrapper(self.f, **self.options)
File "F:\ProgramData\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 1695, in __init__
self._reader = parsers.TextReader(src, **kwds)
File "pandas/_libs/parsers.pyx", line 562, in pandas._libs.parsers.TextReader.__cinit__
File "pandas/_libs/parsers.pyx", line 790, in pandas._libs.parsers.TextReader._get_header
UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 0-1: invalid continuation byte
2.解决问题,推荐使用xlrd这个模块来读取excel文件。
import xlrd
#打开EXCEL文件
excel = xlrd.open_workbook('C:\patents.xlsx')
#获取第一个sheet
sheet = excel.sheets()[0]
#打印第i行数据
print(sheet.row_values(i))
#打印第j列数据
print(sheet.col_values(j))