Search code examples
pythonpython-2.7xlrdxlwt

How to read the same data from excel sheet to the textfile in Python


This code actually is working fine but the output showing is different because the excel sheet were present in some values like int, float but after running the script the output showing like given below. I dont need .0 with that value. I want exact values which is there in input.

  Rows  Column  2   6
   a    cd  21
   b    cd  11  4
   c    cd  22  3
   s    cd  4.1 2
   e    cd  4   1

This is the code which showing some wrong value

import xlrd
import xlwt
workbook=xlrd.open_workbook("xxx.xls")
sh=workbook.sheet_by_index(0)
print sh.nrows
print sh.ncols
n=0
i=0
file=open("xx.txt","w")

for n in range(sh.nrows):
    for i in range(sh.ncols):
        data =sh.cell_value(n,i)
        print  data,
        file.write(str(data)+" ")
    print 
    file.write("\n")

Please help me for this issue. I need that whatever it is in excel that should be present in out. This is the output for the above code


Solution

  • Excel treats all numbers as floats. So xlrd is reading all of them as floats and giving them as it is.

    A simple workaround for this is to check if a cell has a float data type & has no floating value, then convert it to int type.

    if isinstance(cell, float) and cell.is_integer():
        cell = int(cell)
    

    So, your code becomes, something like this.

    import xlrd
    workbook = xlrd.open_workbook('data.xls')
    worksheet = workbook.sheet_by_name('Sheet1')
    num_rows = worksheet.nrows 
    num_cells = worksheet.ncols 
    curr_row = -1
    
    with open("xxx.txt", "w") as fh:
        for row in range(num_rows):
            for column in range(num_cells):
                data = worksheet.cell_value(row, column)
                if isinstance(data, float) and data.is_integer():
                    data = int(data)
            fh.write(str(data) + " ")
        fh.write("\n")
    

    And the output will be:

    Rows Column 34.5 6
    a cd 54 5
    b cd 22.3 4
    c cd 56 3
    s cd 677.1 2
    e cd 32 1
    

    Note: If your input file has floating numbers like 6.0 they will be converted to 6 by default.