java调用浏览器导出csv文件

百度了一圈,csv大都是导出和下载分开的,然后根据别人的博客改了改,在此感谢大佬们的付出

js以及jsp

<a href="#" onclick="exportData()" class="easyui-linkbutton"
 iconCls="icon-save">导出</a>

function exportData(){
    location.href=basePath +
     "/exportAction.do?action=export";
}

CSV工具包(自己改成了傻瓜式拿来即用的东西)

    /**
     * @param response
     * @param map   对应的列标题
     * @param exportData    需要导出的数据
     * @param fileds    列标题对应的实体类的属性
     * @throws IOException
     */
    @SuppressWarnings({ "resource", "rawtypes", "unchecked" })
    public static void exportFile(HttpServletResponse response,
            HashMap map, List exportData, String fileds[])
            throws IOException {
        try {
            // 写入临时文件
            File tempFile = File.createTempFile("vehicle", ".csv");
            BufferedWriter csvFileOutputStream = null;
            // UTF-8使正确读取分隔符","
            csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile), "GBK"), 1024);
            // 写入文件头部
            for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator.hasNext();) {
                java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
                csvFileOutputStream.write((String) propertyEntry.getValue() != null ? new String(((String) propertyEntry.getValue()).getBytes("GBK"), "GBK") : "");
                if (propertyIterator.hasNext()) {
                    csvFileOutputStream.write(",");
                }
            }
            csvFileOutputStream.write("\r\n");
            // 写入文件内容,
            // ============ //:Arraylist<实体类>填充实体类的基本信息==================
            for (int j = 0; exportData != null && !exportData.isEmpty()
                    && j < exportData.size(); j++) {
                // RealTimeSO2 t = (BankWageMonth) exportData.get(j);
                Class clazz = exportData.get(j).getClass();
                String[] contents = new String[fileds.length];
                for (int i = 0; fileds != null && i < fileds.length; i++) {
                    String filedName = toUpperCaseFirstOne(fileds[i]);
                    Object obj = null;
                    try {
                        Method method = clazz.getMethod(filedName);
                        method.setAccessible(true);
                        obj = method.invoke(exportData.get(j));
                    } catch (Exception e) {

                    }
                    String str = String.valueOf(obj);
                    if (str == null || str.equals("null"))
                        str = "";
                    contents[i] = str;
                }

                for (int n = 0; n < contents.length; n++) {
                    // 将生成的单元格添加到工作表中
                    csvFileOutputStream.write(contents[n]);
                    csvFileOutputStream.write(",");
                }
                csvFileOutputStream.write("\r\n");
            }

            csvFileOutputStream.flush();

            /**
             * 写入csv结束,写出流
             */
            java.io.OutputStream out = response.getOutputStream();
            byte[] b = new byte[10240];
            java.io.File fileLoad = new java.io.File(tempFile.getCanonicalPath());
            response.reset();
            response.setContentType("application/csv");
            String trueCSVName="导出数据.csv";
            response.setHeader("Content-Disposition", "attachment;  filename="+ new String(trueCSVName.getBytes("GBK"), "ISO8859-1")); 
            long fileLength = fileLoad.length();
            String length1 = String.valueOf(fileLength);
            response.setHeader("Content_Length", length1);
            java.io.FileInputStream in = new java.io.FileInputStream(fileLoad);
            int n;
            while ((n = in.read(b)) != -1) {
                out.write(b, 0, n); // 每次写入out1024字节
            }
            in.close();
            out.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将第一个字母转换为大写字母并和get拼合成方法
     * 
     * @param origin
     * @return
     */
    private static String toUpperCaseFirstOne(String origin) {
        StringBuffer sb = new StringBuffer(origin);
        sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
        sb.insert(0, "get");
        return sb.toString();
    }

参考资料:http://blog.csdn.net/nihaoqiulinhe/article/details/53838874

然后贴一下servlet调用的方法吧

// 创建CSV写对象
        List<RealTimeSO2> exportData = new ArrayList<RealTimeSO2>();
        String xhLxComb="output";
        String startTime="2017-08-02 09:01:44";
        String gnId="21";
        exportData = new SO2DataSelService().listSO2Data(xhLxComb, gnId, startTime);//调用service查询数据
        HashMap map = new LinkedHashMap();
        map.put("1", "第一列");
        map.put("2", "第二列");
        map.put("3", "第三列");
        map.put("4", "第四列");
        String fileds[] = new String[] { "facName", "jzName" , "xhLx","recDate","so2" };
        CVSUtils.exportFile(response, map, exportData, fileds);//直接调用

最后来个图

这里写图片描述

这个真的是最后了

因为要传多个参数到后台,然后ajax捣鼓了下不行,百度了下,貌似这种调用浏览器下载要form表单提交才行。。。。

jsp

<a href="#" onclick="exportData()" class="easyui-linkbutton"  iconCls="icon-save">导出</a>

js

/**
 * 导出功能
 */
function exportData() {
    var exportURL=basePath + "/sO2DataSelAction.do?action=export";
    var temp1=$("#xhLxComb").combobox('getValue');
    //temp1、temp2、temp3这三个是传向后台的值
    var temp2=$("#gnCombobox").combobox('getValue');
    var temp3=$('#startTime').datetimebox('getValue');

    /**
     * 使用form表单来发送请求 
     * 1.method属性用来设置请求的类型——post还是get 
     *2.action属性用来设置请求路径
     *3.后台可以根据request.getParameter(XXX)来获取对应name的值。
     * 
     */
    var form = $("<form>");// 定义一个form表单
    form.attr("style", "display:none");
    form.attr("target", "");
    form.attr("method", "post"); // 请求类型
    form.attr("action", exportURL); // 请求地址

    var input1 = $("<input>");
    input1.attr("type", "hidden");
    input1.attr("name", "temp1");
    input1.attr("value", temp1);
    form.append(input1);
    var input2 = $("<input>");
    input2.attr("type", "hidden");
    input2.attr("name", "temp2");
    input2.attr("value", temp2);
    form.append(input2);
    var input2 = $("<input>");
    input2.attr("type", "hidden");
    input2.attr("name", "temp3");
    input2.attr("value", temp3);
    form.append(input2);
    $("body").append(form);// 将表单放置在web中
    form.submit();// 表单提交
    form.remove();
}

猜你喜欢

转载自blog.csdn.net/qq_39578388/article/details/79423497