简体   繁体   English

使用openpyxl(python)在列中进行HEX-BIN转换的多行写入

[英]Multi-row writing of HEX-BIN conversion in a column with openpyxl (python)

My goal is to convert the cell's value (for each row in a certain range in column E) from HEX to BIN and write the BIN in column N for each row.我的目标是将单元格的值(对于 E 列中某个范围内的每一行)从 HEX 转换为 BIN 并将 BIN 写入每行的 N 列中。 There is no problem with the conversion itself as well as writing the BIN value to a certain cell.转换本身以及将 BIN 值写入某个单元格都没有问题。 But I have issues with the iteration through the rows.但是我在通过行进行迭代时遇到问题。 Just to clarify: I want the HEX code in E1 printed in BIN code in N1, the value in E2 being printed in N2, and so on澄清一下:我希望 E1 中的 HEX 代码以 N1 中的 BIN 代码打印,E2 中的值以 N2 打印,依此类推

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

Here is my code:这是我的代码:

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") 

The error that I get is:我得到的错误是:

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'`

I tried using a tuple converting function but that did not change the outcome.我尝试使用元组转换函数,但这并没有改变结果。

It would be great if you could show me a way to overcome this error.如果你能告诉我克服这个错误的方法,那就太好了。 Thank you!谢谢!

Correct Implementation:正确实施:

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") 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM