Search code examples
python-3.xexceltext-filesopenpyxl

How to copy data from excel to text file using python


I'm trying to copy data of first two rows from excel and copy to text/.DAT file. Using openpy excel but failing when copying data to .DAT file. I'm getting below

openpyxl.utils.exceptions.InvalidFileException: openpyxl does not support .dat file format, please check you can open it with Excel first . Supported formats are: .xlsx,.xlsm,.xltx,.xltm

My code:

    import openpyxl                                                                                        
    workbook = openpyxl.load_workbook('TestFile.xlsx')                                                           
    ws = workbook['Output']                                                                                   
    for row in ws.rows:                                                                                                         
      with open(row[0].value + 'textfile.txt', 'w') as outfile:                                            
        outfile.write(row[1].value)   

Solution

  • This is probably the easiest way to convert an Excel file to a text file.

    import pandas as pd
    
    with open('C:\\test.txt', 'w') as file:
        pd.read_excel('C:\\excel.xlsb').to_string(file, index=False)
      
    # To limit the number of rows read from the Excel file, you can do something like this.
    data = pd.read_excel(filepath, header=0,  skiprows=4, nrows= 20, use_cols = "A:D")