How to export CSV file in Struts2

I'm exporting .xlsx file and Now I want to export .csv file.

I tried to find solution for this but I think none of those are fit for my situation.

Below is my codes

action mapping:

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


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

These works well and I'm trying to export .csv file instead of .xlsx file for web(not saving in local) so that users can download it.

Where should I start ?

Any comment would be appreciated. Thanks.

1 answer

  • answered 2019-06-25 09:33 Youssef Najeh

    Here is a util class to manipulate CSV:

    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, ' ');
        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) {
                if (customQuote == ' ') {
                } else {
                first = false;

    So You clous use it in your code like :

        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 =
           .map(obj -> obj.getYourAttr())
            CSVUtils.writeLine(writer, strings);
            return SUCCESS;
            }catch(Exception e){
                return ERROR;