Reading a cell value that contains a formula returns 0.0 when using xlrd

前端 未结 2 989
再見小時候
再見小時候 2021-02-19 10:31

I try to read a cell value, say E5 and E5 in the excel sheet contains a formula \'=(A29 - A2)\'. I use the following code and it returns me 0.00 instead of the

2条回答
  •  滥情空心
    2021-02-19 11:17

    There is a difference between a cell with a value of zero and an empty cell. To test for this in openpyxl you have to check for TYPE_NULL and also check the value for None, since the TYPE_NULL and TYPE_STRING use the same value 's'. This seems like a bug to me. Perhaps openpyxl will chose a unique value for TYPE_NULL in the future.

    def use_openpyxl():
        import openpyxl
        print ("Using openpyxl:")
        wb = openpyxl.load_workbook('cell_formula_test.xlsx')
        ws = wb.get_sheet_by_name('Sheet1')
        for row in ws.rows:
            for cell in row:
                if (cell.data_type == openpyxl.cell.Cell.TYPE_NULL) and (cell.value == None):
                    continue
                print ("  %s:%s:%s" % (cell.address, cell.data_type, cell.value))
    

    In xlrd the cell_type does have a unique type for empty cells, so the checking is more straight forward.

    def use_xlrd():
        import xlrd
        print ("Using xlrd:")
        wb = xlrd.open_workbook('cell_formula_test.xlsx')
        ws = wb.sheet_by_name('Sheet1')
        for i in range(ws.nrows):
            for j in range(ws.ncols):
                if ws.cell_type(i, j) != xlrd.XL_CELL_EMPTY:
                    print ("  (%d, %d):%s:%s" % (i, j, ws.cell_type(i, j), ws.cell_value(i, j)))
    

提交回复
热议问题