Create excel on server side from db query and save as doc attachment

Is there any example of creating excel file on server side from a custom db query.

I would like to create an excel file and attach it to a document all on the server side. Just like what does, but instead of returning the file in the response, save it as an attachment.