Search code examples
pythonxmlxlrd

Python - creating XML by reading XML resulting "number:" word in file.write


I'm new to Python. I'm trying to generate xml file with the code below:

file = open("filename.xml","w")
workbook = xlrd.open_workbook('data.xlsx')
worksheet = workbook.sheet_by_name('sheet1')
value = worksheet.cell(1, 2)
file.write("<raml xmlns="'"raml21.xsd"'" version="'"2.1"'">")
file.write("    <cmData scope="'"all"'" type="'"plan"'">")
file.write("        <managedObject class="'"BTS"'" distName="'"ID-%s"'" operation="'"create"'" version="'"1891"'">" % str(value))

But then the output is like this:

<managedObject version="1891" operation="create" distName="ID-number:1900.0" class="BTS">

The value of cell(1,2) should be 1900. Why is the output in the file "number:1900.0"? I was expecting it 1900 only. How do I fix this?


Solution

  • You are using the method cell(rowx, colx), which returns a Cell object.
    That's why str(value) in your code returns number:1900.0.

    You want to use the method cell_value(rowx, colx), which returns value of the cell. But you still will get a float number. So if you expect value to be integer, you can cast it like this:

    value = worksheet.cell_value(1, 2)
    id = int(value)
    

    Alternatively, you can use the attribute value of the Cell object.
    For example:

    value = worksheet.cell(1, 2).value
    id = int(value)