Quote:
'System.OutOfMemoryException'
This means that your query do not fit in memory, the only solution is to split your single query into multiple partial queries, no matter what.
First query is records from 1 to 1000
Second query is records from 1001 to 2000
...
https://www.sqlshack.com/introduction-pagination-sql-server/[
^]
Pagination with OFFSET / FETCH : A better way[
^]
As to write in Excel Sheet, you know where you stop on previous piece, just continue on next row.