python openpyxl 中的对齐格式不正确

Align is not in correct format in python openpyxl

我在 python 中尝试了一个程序来从 excel 中读取数据,当我从 Excel 中检索数据时,它没有以正确的格式显示。

这是我的样本excel数据:

这是我的代码

import os
os.getcwd()
import openpyxl
wb=openpyxl.load_workbook('sample.xlsx')
type(wb)
wb.get_sheet_names()
sheet=wb.get_sheet_by_name('Sheet1')
sheet.title
columns=3
rows=3
for r in range(1,rows+1):
    for c in range(1,columns+1):
            d=sheet.cell(row=r,column=c)
            print('%-8s'%d.value , end='')
            print('')

我想要这样的输出

ID      Name    age     
1       Sam     12      
2       Arun    12  

但我是这样的:

ID      
Name    
age     
1       
Sam     
12      
2       
Arun    
12  

问题出在第二个 print(''),它会在显示数据后导致不必要的换行。

for r in range(1,rows+1):
    for c in range(1,columns+1):
        d=sheet.cell(row=r,column=c)
        print('%-8s'%d.value , end='')
        print('')                         <------There's the error

每次数据打印后执行,而不是每行执行。

for r in range(1,rows+1):
    for c in range(1,columns+1):
        d=sheet.cell(row=r,column=c)
        print('%-8s'%d.value , end='')
    print('')

只需将其拉回一个缩进级别即可在每行后调用它