I'm working on a module that imports a Xlsx file and inserts the rows to database. Everything works fine, except PhpSpreadsheet throws the error Unable to identify a reader for this file when my uploaded file is in public. This error doesn't happen when the file is in base_path(). Why is this happening? Below is my code:

public function submitForm(array &$form, FormStateInterface $form_state) {
    $connection = \Drupal::database();
    $fid = $form_state->getValue("xlsx_upload");
    $input = File::load(reset($fid));
    $uri = \Drupal::service('file_system')->realpath($input->getFileUri());
    //$uri = '/home/joe/file.xslx'; <--- this works perfectly.
    $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile($uri);
    $spreadsheet = $reader->load($filename);
    $dataArray = $spreadsheet->getActiveSheet()->toArray();
    $connection->query("SET NAMES utf8");
    foreach ($dataArray as $dataItem) {
        'stokkodu'      => $dataItem[0],
        'logo'          => $dataItem[1],
        'resim1'        => $dataItem[2],
        'grupkodu'      => $dataItem[3],
        'grupadi'       => $dataItem[4],
        'grupindex'     => $dataItem[5],
        'paketadedi'    => $dataItem[6],
    drupal_set_message('Excel verisi veritabanına eklendi.');

EDIT: The above code throws "PHP message: Uncaught PHP Exception InvalidArgumentException: "File "" does not exist ." at File.php line 137", even though line 137 throws an exception saying it's not a file, but \dpm(is_file($uri)) returns TRUE.


Looks like PhpSpreadsheet can't read URIs, but only file paths. You need to find the path to the file on the system.

$real_path_to_file = \Drupal::service('file_system')->realpath($file->getFileUri());

(Ideally you'd inject file_system and not call this service statically.)

  • Comments are not for extended discussion; this conversation has been moved to chat.
    – Clive
    Feb 2 '19 at 15:26
  • @Emil Johnsson your suggestion works just perfect.
    – MiharbKH
    Jan 28 '20 at 8:40

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.