Search code examples
pythonxlsxxlrd

First time Python user confused about xlrd error


I need to make a python script that takes 2 pieces of info from each row of an excel sheet and pastes it into a specific line of a txt file(formatted as c file). I used a lot of online resources to create this but facing this error. I'm a complete beginner to Python so if you could help, I'd greatly appreciate it. Thanks!

import xlrd
import os.path

from xlrd import sheet

workbook = xlrd.open_workbook(os.path.join('C:\\Users\\mushtay\\Desktop', 'RDMControls_XCP.xlsx'))
worksheet = workbook.sheet_by_name('ShaftSpeed_SWC')

i = 1

while worksheet.cell(0, i).value == xlrd.empty_cell.value:
    exit()
else:
    Xi = sheet.cell(0, i)
    Yi = sheet.cell(8, i)
    i = i + 1

while i > 1:
    with open("C:\\Users\\mushtay\\Desktop\\Cal0_ROMVariables.c", "r") as f:
        contents = f.readlines()

    contents.insert(17, "Xi-Yi\n")

    with open("C:\\Users\\mushtay\\Desktop\\Cal0_ROMVariables.c", "w") as f:
        contents = "".join(contents)
        f.write(contents)
    i = i - 1

These are the errors I'm getting

"C:\Users\mushtay\Desktop\Python Project\blegh\Scripts\python.exe" C:/Users/mushtay/PycharmProjects/pythonProject/main.py
Traceback (most recent call last):
  File "C:/Users/mushtay/PycharmProjects/pythonProject/main.py", line 7, in <module>
    workbook = xlrd.open_workbook(os.path.join('C:\\Users\\mushtay\\Desktop', 'RDMControls_XCP.xlsx'))
  File "C:\Users\mushtay\Desktop\Python Project\blegh\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

Process finished with exit code 1

Solution

  • per https://pypi.org/project/xlrd/

    This library only handles .xls, not .xlsx

    It recommends using http://www.python-excel.org/ to find an alternative library.

    I am a fan of xlwings so I can put Python directly into my workbooks, but openpyxl and xlsxwriter are great libraries as well.

    I do like the work-around of using an older version for one-off, but if this is something to survive long-term or referenced in the future for new code you would probably be better off going to a different library.