我的目标是将单元格的值(对于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'`
我尝试使用元组转换功能,但是并没有改变结果。
如果您能向我展示一种克服此错误的方法,那就太好了。谢谢!
正确的实现:
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")