这是我必须从Excel文件中提取数据的代码:
import xlrd
# Give the location of the file
location = ("C:/Users/congo/Documents/PythonScriptTest.xlsx")
# To open workbook
workbook = xlrd.open_workbook(location)
sheet = workbook.sheet_by_index(0)
# Looping through rows and columns of excel file
for i in range(sheet.nrows):
for j in range(sheet.ncols):
print(sheet.cell_value(i, j))
它正在工作,但是没有按照我想打印的方式打印数据。这是如何打印的:
但是我希望它以与Excel中相同的行和列顺序打印。这是它们在Excel中的排序方式:
我可以用Excel中看到的以行和列打印数据的任何方式吗?谢谢!
Pandas是将Excel数据导入Python的很好的工具。这应该工作:
import pandas as pd
df = pd.read_excel("C:/Users/congo/Documents/PythonScriptTest.xlsx")
print(df)
您正在遍历行和列,并且正在打印每个元素,要打印完整的行,您可以执行类似的操作
# Looping through rows and columns of excel file
for i in range(sheet.nrows):
for j in range(sheet.ncols):
print(sheet.cell_value(i, j), end='\t')
print('\n')
您可以使用
print(pd.read_excel('PythonScriptTest.xlsx'))
每个print
语句都会打印换行符,使控制台继续进行到下一行的开头。
如果要在同一行上打印更多内容,请在单个命令中组合要打印的内容,例如:
print('a', 'b')
或使用其他命令,例如:
import sys
sys.stdout.write('a')
sys.stdout.write('b')
如果使用sys.stdout.write()
,请记住,写'\n'
会像换行print
一样打印换行符。
sys.stdout.write('just like print\n')
您还可以告诉print
自己不要写换行符:
print('a', end='')