Like what we’re doing? Star us on GitHub!

export list to csv, xlsx

kosmo
3 weeks ago
5

Hello, Is there any option to export collection list to external file?

  • thgh
    3 weeks ago

    Built this yesterday:


    import { stringify } from 'csv-stringify/sync'
    import archiver from 'archiver'
    
    export const downloadEndpoint: Endpoint = {
      path: '/download-zip',
      method: 'get',
      async handler(req, res, next) {
        // Only admins allowed
        if (!isAdmin(req.user)) return next()
    
        const result = await req.payload.find({
          collection: 'widgets',
          where, // derived from query params
          limit: 1000, // sanity check
        })
    
        const archive = archiver('zip', { zlib: { level: 9 } })
        archive.pipe(res)
        res.setHeader('Content-Type', 'application/zip')
        res.setHeader('Content-Disposition', 'attachment; filename=widgets.zip')
    
        const csv = stringify(result.docs, { header: true })
        archive.append(csv, { name: 'test.csv' })
        archive.finalize()
      },
    }
  • kosmo
    3 weeks ago

    Thanks for answer! đź’š ,


    Do you have some extra configuration for archiver? When I'm trying use it, I have a lot of errors

  • thgh
    3 weeks ago

    If it's a webpack error, you should add archiver to payloadconfig.admin.webpack.resolve.alias so ot doesn't try to bundle it. Otherwise not other config



    You could consider to skip the zipping and return the csv straight away

  • kosmo
    3 weeks ago

    thank you so much! Im going to try it

Open the post
Continue the discussion in Discord
Can't find what you're looking for?
Get help straight from the Payload team with an Enterprise License.Learn More