【问题标题】:Getting wrong value when reading an xlsx file using openpyxl使用 openpyxl 读取 xlsx 文件时获取错误值
【发布时间】:2021-04-06 10:07:56
【问题描述】:

我正在尝试使用 openpyxl 从包含公式的 xlsx 文件中读取值;但是,我注意到对于某些单元格,我得到了错误的值。

这是 XLSX 示例:

这是我得到的结果:

代码:

 wb = openpyxl.load_workbook(excel_file, data_only=True)

    # getting all sheets
    sheets = wb.sheetnames
    print(sheets)

    # getting a particular sheet
    worksheet = wb["Feuil1"]
    print(worksheet)

    # getting active sheet
    active_sheet = wb.active
    print(active_sheet)

    # reading a cell
    print(worksheet["A1"].value)

    excel_data = list()
    # iterating over the rows and
    # getting value from each cell in row
    for row in worksheet.iter_rows():
        row_data = list()
        for cell in row:
            #cell.number_format='0.0########'
            print(cell.number_format)
            row_data.append(str(cell.value))
            print(cell.value)
        excel_data.append(row_data)

    return render(request, 'myapp/index.html', {"excel_data":excel_data})

【问题讨论】:

  • 有什么问题?该值是一个浮点数,但您可以将其四舍五入到所需的精度。
  • @CharlieClark well 53*1,2 应该正好等于 63,6,所以我想知道为什么我得到的结果是 63,59999,特别是因为我需要这些值准确到最高学历。

标签: python openpyxl xlsx


【解决方案1】:

嘿,你想从一个打开的 excel 文件中得到什么意味着你要选择哪种格式 数据, 这是我使用 xlrd 从 excel 文件中获取数据的答案。

 import xlrd
 from xlrd import open_workbook
    
    fp = tempfile.NamedTemporaryFile(delete= False, suffix=filetype)
    fp.write(binascii.a2b_base64(selected file))
    workbook = xlrd.open_workbook(file name)
    sheet = workbook.sheet_by_name(sheet name)
    row = [c or '' for c in sheet.row_values(header_row)]
    first_row = [] 
     for col in range(sheet.ncols):
        first_row.append(sheet.cell_value(0,col) )
    archive_lines = []
       for row in range(1, sheet.nrows):
          elm = {}
          for col in range(sheet.ncols):
             elm[first_row[col]]=sheet.cell_value(row,col)
          archive_lines.append(elm)

【讨论】:

  • 我不明白为什么在 excel (53*1,2=63,6) 中正确计算了该值,但是当我使用 openpyxl 检索数据时,我得到了错误的值 (63.599999999999994) .
  • 但是你可以使用openpyxl 为什么不使用xlrd
  • 我的理解是xlrd只支持xls格式,不支持xlsx。 .
  • 不,兄弟,我可以将 xlrd 用于 .xlsx 或 .xls 两种格式,您可以尝试一下
  • 好吧,我尝试使用 xlrd,但出现异常“Excel xlsx 文件;不支持”。
猜你喜欢
  • 1970-01-01
  • 2021-08-27
  • 2023-03-27
  • 2021-10-11
  • 2022-01-22
  • 2016-12-05
  • 2020-10-26
  • 1970-01-01
  • 2021-07-01
相关资源
最近更新 更多