0

I am tring to read a very simple excel sheet. And I have this to read the excel sheet:

import xlrd
import pandas

workbook=pandas.ExcelFile(r'C:\Users\Documents\python\docs\Book1.xlsx', engine='openpyxl')
sh=workbook.sheet_names(0)
print(sh.rows) 
print (sh.ncols)
n=0
i=0
file=open("xxx.txt","w")
for n in range(sh.nrows):
    for i in range(sh.ncols):
        data =sh.cell_value(n,i)+" "
        print (data),
        file.write(data+" ")
    print 
    file.write("\n")

But I get this error:

Traceback (most recent call last):
  File "c:\Users\Documents\python\code\textFromExcel.py", line 5, in <module>
    sh=workbook.sheet_names(0)
TypeError: 'list' object is not callable

So my question is: How to resolve this?

Thank you

Yes. But if I do this:

import xlrd
import pandas

workbook=pandas.ExcelFile(r'C:\Users\engel\Documents\python\docs\Book1.xlsx', engine='openpyxl')
sh=workbook.sheet_names[0]
print(sh.rows) 
print (sh.ncols)
n=0
i=0
file=open("xxx.txt","w")
for n in range(sh.nrows):
    for i in range(sh.ncols):
        data =sh.cell_value(n,i)+" "
        print (data),
        file.write(data+" ")
    print 
    file.write("\n")

Then I get this error:

File "c:\Users\engel\Documents\python\code\textFromExcel.py", line 6, in <module>
    print(sh.rows)
AttributeError: 'str' object has no attribute 'rows'
3
  • 3
    Most likely sh=workbook.sheet_names[0] Commented Aug 31, 2022 at 21:24
  • Then I get this error: - why do you think the string has a rows attribute?` Commented Aug 31, 2022 at 23:00
  • 'str' object has no attribute, Commented Aug 31, 2022 at 23:04

1 Answer 1

1

From the perspective or writing code, the shortest way to read a file would be using pandas.read_excel(filename, sheetname) as this would read the whole sheet directly into a pandas dataframe in one shot.

import pandas as pd
df = pd.read_excel('Readfile.xlsx','Sheet1')
print(df)

To write the contents of the dataframe into a file, use to_excel().

import pandas a pd
df.to_excel('OutputFile.xlsx','Sheet1')

Note that if the file already exists and there is data in Sheet1, this will overwrite the data there. You can overlay the new data on top of existing data using overlay in newer versions. Check this link if that is your requirement.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.