Search code examples
pythonexcelfilecell

Python file not opening correctly in Excel (values aren't in the cells)


I wrote a Python code with the file.write command, so my calculated values are all written into a file. When prompted to open the file, I selected Microsoft Excel as the application to open it.

Here is the code:

for i in range (0,len(result)-1):  
...  file.write("%s " % result[i][0][0])     
...  file.write("%s \n" % result[i][0][1])
...  branch = result[i]
...  NumPoints = len(branch)  
...  for j in range (biggestHWS, NumPoints - biggestHWS):
...      HWS = biggestHWS # reset HWS
...      file.write("%s " % result[i][0][0])   
...      file.write("%s " % result[i][0][1])
...      file.write("%s \n" % j)
...      while HWS > 0:  
...              length = HWS * 2 * 10   
...              d = math.sqrt((branch[j-HWS][3] - branch[j+HWS][3]) ** 2 + (branch[j-HWS][4] - branch[j+HWS][4]) ** 2)
...              s = length / d
...              file.write("%s " % s)   
...              HWS = HWS - 1   
...      file.write(" \n")   
file.close()    

The values show up in the Excel spreadsheet but are not in the cells - it looks like they are just printed on top of the cells but not inside the cells. I am a beginner Python programmer, so I'm not sure what's going on.

Is there a way to correctly open the file so that the values are in Excel cells, or do I have to write the data into an Excel spreadsheet in my code?


Solution

  • If you want to output an Excel file from a Python script, you should probably use a module such as Xlsxwriter or xlwt. Otherwise you will need to write your data as a csv file or something and import it into Excel.