Good code always checks if function calls fail. To do that, inspect the return values and show error messages upon failures.
If you do that, you will be informed that your query fails because you are passing an invalid SQL command:
SELECT * FROM tname P WHERE 1
A valid command would be something like
SELECT * FROM tname WHERE P=1
Similar for the appending of
" AND 1 "
which is also not valid.
Finally, you are not creating an Excel file. You are creating a TAB separated text file which is recognised by Excel when importing. But it is not an Excel file and should be therefore not announced as such.