现在的位置: 首页 > 综合 > 正文

利用Ostermiller生成CSV方法

2018年01月10日 ⁄ 综合 ⁄ 共 1833字 ⁄ 字号 评论关闭

//生成数据

private List<String> exportSummaryCsvContent(List<String[]> contentArrayList, HttpServletResponse response){

List<String> outputDataList = new ArrayList<String>();
for (String[] contentArray : contentArrayList) {
contentArray = replaceSpecialCharacter(contentArray);
       String outputContent = 
       contentArray[0]+"," +     
       contentArray[1]+"," +     
       contentArray[2]+"," +     
       contentArray[3]+"," +    
       contentArray[4]+"," +     
       contentArray[5]+"," +
       contentArray[6]+"," +
       contentArray[7];  
       outputDataList.add(outputContent);
}
return outputDataList;

}

//替换内容的逗号和双引号

private String[] replaceSpecialCharacter(String[] contents) {
    String[] replacedArray = new String[contents.length];
    for (int i=0, m=contents.length; i<m ; i++) {
    replacedArray[i] = contents[i].replaceAll(",", "%2C").replaceAll("\"", "");
    }
    return replacedArray;
    }

//开始生成CSV文件

package com.utils;

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

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.Ostermiller.util.CSVPrinter;

public class CsvFileParser {

    private CsvFileParser() {
    }
    
    public static boolean parseDataListToCsv(List<String> dataList, HttpServletResponse response) throws IOException {
    ServletOutputStream out = response.getOutputStream();
response.setHeader("Charset","UTF-8");
response.setCharacterEncoding("UTF-8");
byte[] bs = new byte[3];
bs[0] = (byte)0XEF;
bs[1] = (byte)0XBB;
bs[2] = (byte)0XBF;

response.getOutputStream().write(bs);
CSVPrinter csvp = new CSVPrinter(out);
csvp.setAlwaysQuote(true);
    try {
    for (String data : dataList) {
    String[] contents = data.split(",");
    String[] replacedContents = new String[contents.length];;
    for (int i=0,m=contents.length; i<m; i++) {
    replacedContents[i] = contents[i].replaceAll("%2C", ",");
    }
csvp.write(replacedContents);
csvp.writeln();
    }
        } catch (Exception e) {
        e.printStackTrace();
            return false;
        } finally {
        }
        return true;
    }
}

抱歉!评论已关闭.