簡體   English   中英

將 JSON 數據轉換為 Excel 文件 在 Javascript 中下載

[英]Convert JSON Data into Excel File Download in Javascript

我有一個 AJAX POST 請求以 JSON 數組的形式取回數據。 我想將此收到的 JSON 數據轉換為 Excel 文件(不是 CSV)以供下載(單擊按鈕),請幫助。 每個 JSON 行的 JSON 數據可能有空白值和缺失字段。

我在客戶端使用 Javascript 進行了嘗試,但在 Java 服務器端沒有嘗試過,在這種情況下,我將不得不在 AJAX 端點方法中使用 @Produces(MediaType.MULTIPART_FORM_DATA),這是我可以嘗試的,但認為它很復雜。

a) AJAX 請求代碼:

function fileUploadFunction() {

    var file = $('input[name="file"').get(0).files[0];
    var formData = new FormData();

    if(file.name != null) {
        document.getElementById("btnUpload").disabled = false;

        formData.append('file', file);
        $.ajax({
            url : "<%=request.getContextPath()%>/rest/upload/upload",
            type : "POST",
            data : formData,
            cache : false,
            contentType : false,
            processData : false,
            success : function(response) {
                //Store result in Session and Enable Download button
                var cacheString = JSON.stringify(response, null, 2);
                console.log("-----------------> cacheString is: " + cacheString);
                if(cacheString != null && cacheString != "[]") {
                    document.getElementById("download").disabled = false;
                }
                var sessionresponse = sessionStorage.setItem("i98779", cacheString); 

                console.log("response is: " + response);
                console.log("cacheString is: " + cacheString);
                excelDownload(cacheString);
                //createTable(response);
                //https://stackoverflow.com/questions/47330520/how-to-export-json-object-into-excel-using-javascript-or-jquery

            },

            error : function(jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
                alert("Error: " + errorThrown);
            }

        });//ajax ends

    }//if ends

}//Function ends

b) 從 AJAX POST 請求接收的 JSON 樣本數據:

[
    {
    "entityid":2,
    "firstname":"George",
    "lastname":"Bush",
    "ssn":"",
    "city":"Houston",
    "state":"TX",
    "country":"USA",
    "zipcode":""
    },
    {
    "entityid": 8,
    "firstname": "Jim",
    "lastname": "Macron",
    "ssn": "888-88-8888",
    "city": "Paris",
    "state": "NY",
    "country": "France",
    "zipcode": "T789J"
    },
    {
    "entityid": 11,
    "firstname": "Angela",
    "lastname": "Merkel",
    "city": "Saxony",
    "zipcode": ""
    },
    {
    "entityid": 7,
    "firstname": "Donald",
    "lastname": "Trump",
    "ssn": "777-77-7777",
    "city": "Washington D.C.",
    "state": "DC",
    "country": "USA",
    "zipcode": "70000"
    }

]

這是一種從 WebService(Resteasy 實現)生成 excel 的方法,經過測試並且可以正常工作:

@POST
    @Path("/excelpost")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response downloadFilePost( ) throws IOException {

         XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet("Datatypes in Java");
            Object[][] datatypes = {
                    {"Datatype", "Type", "Size(in bytes)"},
                    {"int", "Primitive", 2},
                    {"float", "Primitive", 4},
                    {"double", "Primitive", 8},
                    {"char", "Primitive", 1},
                    {"String", "Non-Primitive", "No fixed size"}
            };

            int rowNum = 0;
            System.out.println("Creating excel");

            for (Object[] datatype : datatypes) {
                Row row = sheet.createRow(rowNum++);
                int colNum = 0;
                for (Object field : datatype) {
                    Cell cell = row.createCell(colNum++);
                    if (field instanceof String) {
                        cell.setCellValue((String) field);
                    } else if (field instanceof Integer) {
                        cell.setCellValue((Integer) field);
                    }
                }
            }

                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                workbook.write(outputStream);
                workbook.close();


            return Response.status(200).header("Access-Control-Allow-Origin", "*")
                    .header("Content-Disposition", "attachment;filename='fileName.xlsx'")
                    .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
                    .header("Access-Control-Allow-Credentials", "true")
                    .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
                    .header("Access-Control-Max-Age", "1209600").entity( new ByteArrayInputStream(outputStream.toByteArray() )).build();


    }

這是管理 Excel 文件的 Maven 依賴項:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>

您可以輕松地添加適當的注釋和 web 參數來管理從您的服務啟動后的文件輸入:

@POST
@Path("/excelpost")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadFilePost(MultipartFormDataInput input)
   .......

讓我知道它是否有幫助...

@Blackjack,下面是代碼...

1)單擊按鈕時調用的函數。 這具有將 Excel 文件傳遞​​給 REST Endpoint 函數的 AJAX 調用:

function fileUploadFunction() {

    var file = $('input[name="file"').get(0).files[0];
    var formData = new FormData();

    if(file.name != null) {
        document.getElementById("btnUpload").disabled = false;

        formData.append('file', file);
        $.ajax({
            url : "<%=request.getContextPath()%>/rest/upload/bulkSearch",
            type : "POST",
            data : formData,
            cache : false,
            contentType : false,
            processData : false,
            success : function(response) {
                //Store result in Session and Enable Download button
                var cacheString = JSON.stringify(response, null, 2);
                console.log("-----------------> cacheString is: " + cacheString);
                if(cacheString != null && cacheString != "[]") {
                    document.getElementById("download").disabled = false;
                }
                var sessionresponse = sessionStorage.setItem("i98779", cacheString); 

                console.log("response is: " + response);
                console.log("cacheString is: " + cacheString);
                //excelDownload(cacheString);
                //createTable(response);
                //https://stackoverflow.com/questions/47330520/how-to-export-json-object-into-excel-using-javascript-or-jquery

            },

            error : function(jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
                alert("Error: " + errorThrown);
            }

        });//ajax ends

    }//if ends

}//Function ends

2)REST端點功能:

@POST 
@Consumes(MediaType.MULTIPART_FORM_DATA) 
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Path("/bulkSearch") 
public Response bulkSearch( 
    @FormDataParam("file") InputStream uploadedInputStream, 
    @FormDataParam("file") FormDataContentDisposition fileDetail) throws IOException { 

    System.out.println("Entered uploadFile method");
    System.out.println("uploadedInputStream is: " + uploadedInputStream);
    System.out.println("fileDetail is: " + fileDetail.toString());

    String returnJSON = null;
    List<User> usersList = null;
    ObjectMapper uploadMapper = new ObjectMapper();

    //System.out.println("File name is: " + fileDetail.getFileName());
    //System.out.println("File size is : " + fileDetail.getSize());
    //System.out.println("File size is : " + fileDetail.getType());

    // check if all form parameters are provided 
    if (uploadedInputStream == null || fileDetail == null) 
        return Response.status(400).entity("Invalid form data").build();

    System.out.println("Checked Input file is ok");

    System.out.println("----------------------------------------------------------------");
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Datatypes in Java");
    Object[][] datatypes = {
            {"Datatype", "Type", "Size(in bytes)"},
            {"int", "Primitive", 2},
            {"float", "Primitive", 4},
            {"double", "Primitive", 8},
            {"char", "Primitive", 1},
            {"String", "Non-Primitive", "No fixed size"}
    };

    int rowNum = 0;
    System.out.println("Creating excel");

    for (Object[] datatype : datatypes) {
        Row row = sheet.createRow(rowNum++);
        int colNum = 0;
        for (Object field : datatype) {
            org.apache.poi.ss.usermodel.Cell cell = row.createCell(colNum++);
            if (field instanceof String) {
                cell.setCellValue((String) field);
            } else if (field instanceof Integer) {
                cell.setCellValue((Integer) field);
            }
        }
    }

        System.out.println("For loop done");

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); //-----> no reference to excel cells here
        System.out.println("outputstream done");
        workbook.write(outputStream);
        System.out.println("workbook.write done");
        workbook.close();
        System.out.println("workbook closed");


    return Response.status(200).header("Access-Control-Allow-Origin", "*")
            .header("Content-Disposition", "attachment;filename='fileName.xlsx'")
            .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
            .header("Access-Control-Allow-Credentials", "true")
            .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
            .header("Access-Control-Max-Age", "1209600").entity( new ByteArrayInputStream(outputStream.toByteArray() )).build();



} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM