Search code examples
javagoogle-drive-apigoogle-sheets-api

Cannot download Google workplace document like GoogleSheet to local using Google API Java


As the Google Drive API document for exporting a Google Sheet stored on GG Drive: https://developers.google.com/drive/api/v3/manage-downloads https://developers.google.com/drive/api/v3/ref-export-formats

I wrote following Java method in order download a GoogleSheet:

public void downloadFileFromDrive() throws Exception {
        String fileId = "1KVNuObZ4ACxKuOFTjf-SKkIgsDAr4L0x5hJzDz_uzhU";
        OutputStream outputStream = new ByteArrayOutputStream();
        serviceDrive().files().export(fileId, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                .executeMediaAndDownloadTo(outputStream);
    }

I ran the program without error. My questions:

  1. Where is the Excel file saved? The document didn't say about destination folder where file saved in local. I searched all files in my PC and didn't see any files I expected

  2. Do I need to declare the path for destination folder for saving file from Drive?


Solution

  • As what @Federico, it's already inside outputStream. But I'd recommend using FileOutputStream since you are outputting it to a file.

    Sample:

    OutputStream outputStream = new FileOutputStream(destinationFolder + fileName);
    serviceDrive.files().export(fileId, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet").executeMediaAndDownloadTo(outputStream);
    outputStream.flush();
    outputStream.close();
    

    Reference: