如何在Struts2中导出CSV文件

时间:2019-06-25 08:37:17

标签: java struts2 export-to-csv

我正在导出.xlsx文件,现在我要导出.csv文件。

我试图为此找到解决方案,但我认为这些都不适合我的情况。

下面是我的代码

动作映射:

<action name="export" class="com.xxx.xxx.xxx.action.myAction" method="excel">
    <result type="excel">
        <param name="template">/xlsTemplate/excel_temaplate.xls</param>
        <param name="beans">gridModel</param>
        <param name="filenameKey">filename</param>
    </result>
</action>

动作:

public String excel() {
        ArrayList<MyVo> resultList = myService.myFunction();
        setGridModel(resultList);
        return SUCCESS;
    }catch(Exception e){
        return ERROR;
    }
}

这些效果很好,我正尝试将.csv文件而不是.xlsx文件导出到Web(不保存在本地)中,以便用户下载。

我应该从哪里开始?

任何评论将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

这是一个用于操作CSV的util类:


import java.io.IOException;
import java.io.Writer;
import java.util.List;

public class CSVUtils {

    private static final char DEFAULT_SEPARATOR = ',';

    public static void writeLine(Writer w, List<String> values) throws IOException {
        writeLine(w, values, DEFAULT_SEPARATOR, ' ');
    }

    public static void writeLine(Writer w, List<String> values, char separators) throws IOException {
        writeLine(w, values, separators, ' ');
    }

    //https://tools.ietf.org/html/rfc4180
    private static String followCVSformat(String value) {

        String result = value;
        if (result.contains("\"")) {
            result = result.replace("\"", "\"\"");
        }
        return result;

    }

    public static void writeLine(Writer w, List<String> values, char separators, char customQuote) throws IOException {

        boolean first = true;

        //default customQuote is empty

        if (separators == ' ') {
            separators = DEFAULT_SEPARATOR;
        }

        StringBuilder sb = new StringBuilder();
        for (String value : values) {
            if (!first) {
                sb.append(separators);
            }
            if (customQuote == ' ') {
                sb.append(followCVSformat(value));
            } else {
                sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
            }

            first = false;
        }
        sb.append("\n");
        w.append(sb.toString());


    }

}

所以您可以在代码中使用它

    public String excel() throws Exception{
        String csvFile = "/Users/mkyong/csv/abc.csv";
        FileWriter writer = new FileWriter(csvFile);
        ArrayList<MyVo> resultList = myService.myFunction();
        List<String> strings = resultList.stream()
       .map(obj -> obj.getYourAttr())
       .collect(Collectors.toList());
        CSVUtils.writeLine(writer, strings);
       writer.flush();
        writer.close();

        return SUCCESS;
        }catch(Exception e){
            return ERROR;
        }
    }