0

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. 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 it didn't work:

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);
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.