一、安装库。

  运行cmd-pip install xlrd

C:\Users\User>pip install xlrd
Collecting xlrd
  Downloading xlrd-2.0.1-py2.py3-none-any.whl (96 kB)
     |████████████████████████████████| 96 kB 10 kB/s
Installing collected packages: xlrd
Successfully installed xlrd-2.0.1
WARNING: You are using pip version 20.2.3; however, version 21.2.4 is available.
You should consider upgrading via the 'e:\python38\python.exe -m pip install --upgrade pip' command.

   二、读取Excel表。

  1、安装库文件和excel表的版本对不上,会出现错误。

  我用xlrd-2.0.1不能访问“..xlsx”的文件,只能访问“.xls”文件。以下是错误代码:

E:\Project\venv\Scripts\python.exe E:/Project/main.py
Traceback (most recent call last):
  File "E:/Project/main.py", line 3, in <module>
    xlsx = xlrd.open_workbook('D:/Book1.xlsx')
  File "E:\Project\venv\lib\site-packages\xlrd\__init__.py", line 170, in open_workbook
    raise XLRDError(FILE_FORMAT_DESCRIPTIONS[file_format]+'; not supported')
xlrd.biffh.XLRDError: Excel xlsx file; not supported

  在PyCharm中安装xlrd-1.2.0的方法:

  “File”菜单-“Setting”进入下图:

Excel读写必备利器xlrd+xlwt_读取excel

通过“-”号删除不想要的版本,再点击“+”号:

Excel读写必备利器xlrd+xlwt_错误代码_02

  在查询中输入“xlwt”,查找到想要的库之后,勾选"Specify version",选择“1.2.0”版本,然后点击“Install Package”按钮安装。

  2、读取代码:

import xlrd

xlsx = xlrd.open_workbook('D:/Book1.xls')
# table = xlsx.sheet_by_name('离疆返钟人员')
table = xlsx.sheet_by_name('Sheet1')
# 下面三种输出方式
print(table.cell(1, 2))
print(table.cell(1, 2).value)
print(table.row(1)[2].value)  # 输出行中的某一列

'''
text:'水电费'
水电费
水电费
'''

   三、写入Excel。

  1、安装xlwt库。方法同上,也可以这PyCharm中导入“import xlwt”,如果没有安装xlwt库,会提示安装。

  2、写入代码:

import xlwt

# 新建一个工作簿对象
new_workbook = xlwt.Workbook()
# 新建一个工作表对象
worksheet = new_workbook.add_sheet('new_test')
# 在工作表的0行0列单元格写入‘OK’
worksheet.write(0, 0, 'OK')
# 保存工作簿到‘d:/test.xls’
new_workbook.save('d:/test.xls')