Score:2

How to return an XLS file to download on form submit

je flag

I am trying to create an XLS file and send it to the browser on a form submit but I cannot figure out how to do it. I am using XLS Serialization module but I'm open to all other suggestions. With this module I successfully created some views with XLS Export feature. But now I have a form and the excel file should be created on form submit depending on the submitted data.

I created the following code but if I send the form, I get no excel file to download:

class MyForm extends FormBase {
  private SerializerInterface $serializer;

  public static function create(ContainerInterface $container) {
    return new static($container->get('serializer'));
  }

  public function __construct(SerializerInterface $serializer) {
    $this->serializer = $serializer;
  }

  // Removed the buildForm() etc for simplicity

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $response = (new StreamedResponse(function () use ($selected_values) {
      $this->serializer->serialize([[1, 2, 3], [4, 5, 6]], 'xlsx');
    }))->send();

    $form_state->setResponse($response);
  }
}
fr flag
"didn't work" ? Not sure what that means exactly ... The only weird thing I can see is the ->send(), but you left out some code and you don't say what the error or problem is.
Елин Й. avatar
je flag
it means when I send the form, I don't get an excel file to download
Score:4
in flag

First off, you need a serializer for xls(x), I used https://www.drupal.org/project/xls_serialization

The following example code should deliver what you need:

public function submitForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValues();
  $filename = "random_file_" . rand() . ".xlsx";

  $response = new StreamedResponse(function () use ($values) {
    echo $this->serializer->serialize([[1, 2, 3], [4, 5, 6]], 'xlsx');
  });
  $response->headers->set('Content-Type', 'application/vnd.ms-excel');
  $response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"');

  $form_state->setResponse($response);
}

I tried that with the XLS encoder provided https://www.drupal.org/project/xls_serialization and it worked.

Good luck!

References:

Елин Й. avatar
je flag
Thank you, I worked out a working solution. But with a bit different and simpler callback function in StreamedResponse. Would you mind if I update your code?
Stefanos Petrakis avatar
in flag
If it's the same approach, yes, please do. Otherwise, this question needs a different answer than mine. Curious in any case! The callback code I wrote in there was based off of your question, perhaps you can update the question and then I can update my answer.
Елин Й. avatar
je flag
Updated the code with the one worked for me. Please check my changes: https://drupal.stackexchange.com/posts/308007/revisions If you want you can still rollback to your version. Thanks.
Stefanos Petrakis avatar
in flag
So, all you needed was the headers' part to get your code working, right?
Елин Й. avatar
je flag
Not only the headers. I also added `echo` to the StreamedResponse callback, and removed the `send()` method that I used at the beginning.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.