【问题标题】:Multi-row writing of HEX-BIN conversion in a column with openpyxl (python)用openpyxl(python)在一列中多行写入HEX-BIN转换
【发布时间】:2020-05-18 22:44:58
【问题描述】:

我的目标是将单元格的值(对于 E 列中特定范围内的每一行)从 HEX 转换为 BIN,并将 BIN 写入每行的 N 列。转换本身以及将 BIN 值写入某个单元格都没有问题。但是我对通过行的迭代有问题。澄清一下:我希望 E1 中的 HEX 代码以 N1 中的 BIN 代码打印,E2 中的值打印在 N2 中,依此类推

A  B  C D  E  F  G  H  I  J  K  L  M  N
           90                         ‭10010000‬
           8A                         ‭10001010‬
           ..                         ....

这是我的代码:

theFile = openpyxl.load_workbook('T013.xlsx')
allSheetNames = theFile.sheetnames 
print("All sheet names {} " .format(theFile.sheetnames)) 
sheet = theFile.active

for row in sheet.iter_rows(min_row=1, max_row=1210,values_only = True): 
    for cell in sheet["E"]: 
        if cell.value is None:
            print("Blank")
        else: 
            inputHEX = str(cell.value) 
            res = "{0:08b}".format(int(inputHEX,16))
            print(res)
            for x in sheet["N1:N1210"]:
                sheet.cell(row=x, column=1).value = str(res) #same error as with res without str 
theFile.save("C:\\Users\\...\\Adapted_T013.xlsx") 

我得到的错误是:

C:\Users\...\Desktop\Practical Part\CAN Python>python ExcelDecode.py
All sheet names ['T013']
Blank
11100001
Traceback (most recent call last):
  File "ExcelDecode.py", line 42, in <module>
    sheet.cell(row=x, column=1).value = res
  File "C:\Users\...\AppData\Local\Programs\Python\Python38-32\lib\site-packages\openpyxl-3.0.3-py3.8.egg\openpyxl\worksheet\worksheet.py", line 235, in cell
TypeError: '<' not supported between instances of 'tuple' and 'int'`

我尝试使用元组转换函数,但这并没有改变结果。

如果您能告诉我一种克服此错误的方法,那就太好了。谢谢!

【问题讨论】:

  • 请包含完整的回溯
  • @CharlieClark:谢谢你的评论!我已经包含了回溯。这有助于理解问题吗?
  • @Nezuko TypeError: '&lt;':你的错误是x in , .cell(row=x,。 xvaluestuple,但 row= 需要 int。删除完整的for x in... 并执行.cell(row=cell.row, column=&lt;index of Column N&gt;)
  • @stovfl:非常感谢您的解释和提示!我能够得到我想要的。真高兴 :-) 谢谢!

标签: python excel binary hex openpyxl


【解决方案1】:

正确实施:

theFile = openpyxl.load_workbook('T013.xlsx')
allSheetNames = theFile.sheetnames 
print("All sheet names {} " .format(theFile.sheetnames)) 
sheet = theFile.active

for row in sheet.iter_rows(min_row=1, max_row=1210,values_only = True): 
    for cell in sheet["E"]:
        if cell.value is not None:
            inputHEX = str(cell.value)
            res = "{0:08b}".format(int(inputHEX,16))
            sheet.cell(row=cell.row, column=14).value = res
    break
theFile.save("C:\\Users\\..\\Adapted_T013.xlsx") 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-25
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多