Hướng dẫn html download xlsx file

I have a react frontend and java server using the Micronaut framework. In the BaseController of my Micronaut Framework, I am creating an XLSX file and then sending the response so that it gets downloaded when called from the frontend code.

Nội dung chính

  • How do I download an XLSX file using Javascript?
  • How do I download an XLSX file?
  • How do I save a .xlsx file as a blob?
  • How do I download an Excel file in HTML?
  • How do you export excel using JavaScript?
  • How fetch data from excel using JavaScript?
  • How do I download a spreadsheet from a website?
  • How do I download Excel as XLS?
  • How do you automate downloading a file from a website using Excel?
  • How do I export BLOB data in Excel?
  • How do I download an Excel file using JavaScript?
  • How do I download an XLSX file?
  • How do I write an XLSX file in JavaScript?
  • How do I download a JavaScript file?

BaseController

@Inject ExportService exportService

@Controller('/abc/api/v1')
@Slf4j
class BaseController implements CachingHandler, CommonUtils {
    @Post('/export/{name}')
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.ALL)
    executeExporter(String name, @Nullable @Body LinkedHashMap payload) {
        def handler = { LinkedHashMap paramMap ->
            List paramMapList = paramMap.get("data") as List
            Byte[] resultBytes = exportService.exportToXLSX(paramMapList, getFileName(getLookupValue(name), paramMap.get("key") as String), true)
            log.info String.format("About to return XLSX file %s for %s",getFileName(getLookupValue(name), paramMap.get("key") as String), name)
            return resultBytes
        }
        def results = handler.call(payload)
        InputStream inputStream = new ByteArrayInputStream(results)
        return new StreamedFile(inputStream, getFileName(getLookupValue(name), payload["key"] as String))
    }
}

ExportService

Note: Using the main method of this class I am able to create a TestReport.xlsx file. XLSXExporter class uses Apache POI library to generate XLSX file.

@Prototype
@Slf4j
class ExportService implements CommonUtils {

    Byte[] exportToXLSX(List response, String fileName, boolean isDelete) {
        def headers = []
        try {
            headers = response[0].keySet()
        } catch(Exception e) {
            e.printStackTrace()
        }
        Map params = [:]
        params[Constants.HEADERS] = headers
        params[Constants.DATA] = response

        XLSXExporter xlsxExporter = new XLSXExporter()
        boolean fileCreated = xlsxExporter.writeData(Constants.DEFAULT_SHEET_NAME, fileName, params)
        if (fileCreated) {
            Byte[] workbookContent = xlsxExporter.getFile(fileName, isDelete)
            return workbookContent
        } else {
            return new Byte[0]
        }
    }

    static void main(String[] args) {
        def param = []
        for (int i in 1..5) {
            def paramMap = [:]
            paramMap["key1"] = "data"+i
            paramMap["key2"] = "data"+i
            paramMap["key3"] = "data"+i
            param.add(paramMap)
        }
        ExportService exportService = new ExportService()
        Byte[] resultBytes = exportService.exportToXLSX(param, "TestReport.xlsx", false)

        /**
            I am able to create a proper TestReport.xlsx file using this main method
        **/
    }
}

I tested the above API from Postman and it is able to download an XLSX file.

Hướng dẫn html download xlsx file

When I call the above export API using my application (javascript), it is able to download an xlsx file but it does not open.

Javascript code to call export API

const exportData = (filteredRows, activity) => {
    let filename = "TestReport.xlsx";
    return axios({
        headers: {
            'Content-type': 'application/json'
         },
        accept:'application/x-www-form-urlencoded',
        url: '/abc/api/v1/export/'+ activity,
        method: 'post',
        data: {
            "key": "8575",
            "type":"userdetails",
            "data":filteredRows
        }
    }).then(resp => {
        var blob = resp.data;
        if(window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveBlob(blob, filename);
        }
        else{
            var downloadLink = window.document.createElement('a');
            downloadLink.href = window.URL.createObjectURL(new Blob([blob], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}));
            downloadLink.download = filename;
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
           }
    });
}

Once I click yes on the above dialog I get below error and nothing gets displayed as opposed to the file downloaded from Postman.

Javascript Download Xlsx File With Code Examples

In this session, we’ll try our hand at solving the Javascript Download Xlsx File puzzle by using the computer language. The code that follows serves to illustrate this point.

const url = window.URL.createObjectURL(
        new Blob([response.data], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        })
      );
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", filename);
 document.body.appendChild(link);
 link.click();
 link.remove();

In order to solve the Javascript Download Xlsx File issue, we looked at a variety of cases.

How do I download an XLSX file using Javascript?

javascript download xlsx file

  • const url = window. URL. createObjectURL(
  • new Blob([response. data], {
  • type: “application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”,
  • })
  • );
  • const link = document. createElement(“a”);
  • link. href = url;
  • link. setAttribute(“download”, filename);

How do I download an XLSX file?

Select File > Save As > Download a Copy. If Excel asks whether to open or save the workbook, select Save. Note: If you select Open instead of Save, the workbook will open in Protected View.

How do I save a .xlsx file as a blob?

var blob = new Blob( [data], {type: “application/vnd. openxmlformats-officedocument. spreadsheetml. sheet;base64,”} ); // Programatically create a link and click it: var a = document.

How do I download an Excel file in HTML?

Example : Download the HTML table in Excel (. csv) format

  • Step 1 : Create the HTML table.
  • Step 2 : Add CSS properties to style the table.
  • Step 3 : Create the download button.
  • Step 4 : Implement Javascript function to download the HTML table in CSV file.
  • Step 5 : Call the Javascript function using onclick event.

How do you export excel using JavaScript?

How to Import and Export Excel XLSX Using JavaScript

  • Set Up the JavaScript Spreadsheet Project.
  • Add Excel Import Code.
  • Add Data to the Imported Excel File.
  • Add a Sparkline.
  • Add Excel Export Code.

How fetch data from excel using JavaScript?

Javascript Excel – Import Data From Excel The Excel file is read into Uint8Array object, which is then passed to the load method exposed by the Excel library. Once the worksheet is loaded into the Excel library object, we can read each cell value and build a JSON array that will be used as the igGrid data source.

How do I download a spreadsheet from a website?

Downloading an Excel spreadsheet from a link in a Web page isn’t complicated: just click the link and the browser saves the associated file to the computer. You can, however, streamline the process so that the computer automatically opens the spreadsheet in the appropriate program after the download completes.

How do I download Excel as XLS?

Select File • Select Save As • Click on Save as type drop-down box arrow • Select Microsoft Excel Workbook\ • Enter File Name ________ . xls • Select OK.

How do you automate downloading a file from a website using Excel?

Type the file list to be downloaded from internet and all URLs corresponding to those files into an Excel sheet.Manual Download:

  • We have to collect and log the URL link for each file in some document.
  • Browse each website and.
  • Click on download file option provided in each of these websites.

How do I export BLOB data in Excel?

Click “Start New Task – Export LOB To Files” at task dialog.

  • then show the wizard. Config.
  • Export.
  • then you can see exporting results.
  • More about MyLobEditor – the tool to batch export MySQL BLOB to excel files. 30-day free trial US$75.0.

How do I download an Excel file using JavaScript?

Downloading Excel File using AJAX in JavaScript When the Download Button is clicked, the DownloadFile JavaScript function is called. Inside the DownloadFile JavaScript function, the URL of the File is passed as parameter to the GET call of the JavaScript XmlHttpRequest call.

How do I download an XLSX file?

To do this:.

Select File > Save As > Download a Copy..

If Excel asks whether to open or save the workbook, select Save. Note: If you select Open instead of Save, the workbook will open in Protected View. Depending on your browser, you may not be asked this..

How do I write an XLSX file in JavaScript?

Creating a Workbook.

var wb = XLSX. utils. book_new(); ... .

wb. SheetNames. ... .

var ws_data = [['hello' , 'world']]; //a row with 2 columns. var ws_data = [['hello' , 'world']]; //a row with 2 columns. ... .

var ws = XLSX. utils. ... .

wb. Sheets["Test Sheet"] = ws; ... .

var wbout = XLSX. write(wb, {bookType:'xlsx', type: 'binary'});.

How do I download a JavaScript file?

So the steps for downloading the file will be:.

Use fetch API to download the script file..

Transform the data to a blob type..

Convert the blob object to a string by using URL. createObjectURL() ..

Create an <a> element to download the string..