Search code examples
javascriptvue.jsexport-to-excel

Issue with export xls file from api to js


I get set of characters instead of real data in the response. But when I click Download file in swagger, everything works fine. Help me to find the problem

function downloadDocFile(data: Blob, ext = 'xlsx', name = 'Export'): void {
  const downloadUrl = window.URL.createObjectURL(new Blob([data]))
  const link = document.createElement('a')
  link.href = downloadUrl
  link.setAttribute('download', `${name}-${DateTime.now().toLocaleString()}.${ext}`)
  document.body.appendChild(link)
  link.click()
  link.remove()
}

const loading = useLoading()
function handleExport() {
  loading.show()
  const url = `/bill-of-material/${bomItems.value[0]?.billOfMaterialId}/available-kits/export-xls`
    
  getApiInstance('kitting')
    .post(url, { responseType: 'blob' })
    .then((data: any) => {
      if (data) {
        downloadDocFile(data)
      }
      loading.hide()
    })
}

Please see screenshots: Responce Image Swagger Image

I tried changing the downloadDocFile and handleExport functions, but nothing worked.


Solution

  • function downloadDocFile(data: Blob, ext = 'xlsx', name = 'Export'): void {
      const downloadUrl = window.URL.createObjectURL(new Blob([data], { type: "application/vnd.ms-excel" }))
      const link = document.createElement('a')
      link.href = downloadUrl
      link.setAttribute('download', `${name}-${DateTime.now().toLocaleString()}.${ext}`)
      document.body.appendChild(link)
      link.click()
      link.remove()
    }
    
    const loading = useLoading()
    function handleExport() {
      loading.show()
      const url = `/bill-of-material/${bomItems.value[0]?.billOfMaterialId}/available-kits/export-xls`
        
      getApiInstance('kitting')
        .post(url, { responseType: 'blob' })
        .then((data: any) => {
          if (data) {
            downloadDocFile(data)
          }
          loading.hide()
        })
    }
    

    Put mime type in creating blob. application/vnd.ms-excel for MS Excel File (.xlsx,. xls)