How to export JavaScript array info to csv (on client side)?

前端 未结 29 1734
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 21:55

I know there are lot of questions of this nature but I need to do this using JavaScript. I am using Dojo 1.8 and have all the attribute info in array, which loo

29条回答
  •  一个人的身影
    2020-11-21 22:31

    Here's how I download CSV files on the client side in my Java GWT application. Special thanks to Xavier John for his solution. It's been verified to work in FF 24.6.0, IE 11.0.20, and Chrome 45.0.2454.99 (64-bit). I hope this saves someone a bit of time:

    public class ExportFile 
    {
    
        private static final String CRLF = "\r\n";
    
        public static void exportAsCsv(String filename, List> data) 
        {
            StringBuilder sb = new StringBuilder();
            for(List row : data) 
            {
                for(int i=0; i0) sb.append(",");
                    sb.append(row.get(i));
                }
                sb.append(CRLF);
            }
    
            generateCsv(filename, sb.toString());
        }
    
        private static native void generateCsv(String filename, String text)
        /*-{
            var blob = new Blob([text], { type: 'text/csv;charset=utf-8;' });
    
            if (navigator.msSaveBlob) // IE 10+
            { 
                navigator.msSaveBlob(blob, filename);
            } 
            else 
            {
                var link = document.createElement("a");
                if (link.download !== undefined) // feature detection
                { 
                    // Browsers that support HTML5 download attribute
                    var url = URL.createObjectURL(blob);
                    link.setAttribute("href", url);
                    link.setAttribute("download", filename);
                    link.style.visibility = 'hidden';
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                }
            }
        }-*/;
    }
    

提交回复
热议问题