Search code examples
pythonexcelcsvxlrd

Read data from excel and write as CSV format to a file - Python


I have a excel sheet which has 5 rows and 5 columns with the below values:

Time   Launch   Login    Password    Signout
00:01   1.26     1.56      5.24        12.3
00:02   1.22     1.55      5.34        2.35
00:03   1.36     1.53      1.24        2.13
00:05   1.46     1.26      2.24        1.32

How can I convert the above data to a csv format and write it to a text file. I'm able to read them from the excel but when I write, they all get combined.

Output Format:

Time,Launch,Login,Password,Signout
00:01,1.26,1.56,5.24,12.3
00:02,1.22,1.55,5.34,2.35
00:03,1.36,1.53,1.24,2.13
00:05,1.46,1.26,2.24,1.32

My Code:

workbook3 = xlrd.open_workbook('C:\Users\aa\Desktop\Report3.xls', logfile=open(os.devnull, 'w'))
worksheet3 = workbook3.sheet_by_index(0)
num_cols3 = worksheet3.ncols
num_rows3 = worksheet3.nrows
for row_index3 in range(0, num_rows3):
    for col_index3 in range(0, num_cols3):
        cell_val= worksheet3.cell(row_index3, col_index3).value
        with open("C:\Users\aa\Desktop\outputfile.txt", 'a') as f:
            f.write(cell_val)
print "Write Completed" 

Kindly guide.


Solution

  • You could try using pandas. It makes what you wanna do super easy.

    import pandas as pd
    filename = "filename.xlsx"
    data = pd.read_excel(filename).to_csv(filename.replace(".xlsx", ".csv"))
    

    Alternatively it's way easier IMO to collect all the data in a 2d array. So something like

    data = []
    for row_index3 in range(0, num_rows3):
        row = []
        for col_index3 in range(0, num_cols3):
            row.append(worksheet3.cell(row_index3, col_index3).value)
        data.append(row)
    with open("C:\Users\aa\Desktop\outputfile.txt", 'w') as f: 
        f.write("\n".join(','.join(map(str, row)) for row in data))
    print "Write Completed"