CSV Excel 亂碼

public class CsvExport {

private static final String SPLIT_LINE_SEPARATOR = "\n";
private List<String> headList;
private List<List<String>> dataList;
private boolean isFirst = false;
private String fileUrl;

private CSVPrinter csvFilePrinter;
private FileWriter fileWriter;

private void init(){
    File file = new File(fileUrl);
    try {
        if (!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        fileWriter = new FileWriter(fileUrl);
        //BOM的UTF-8 頭 防止Excel打開亂碼
        byte[] uft8bom={(byte)0xef,(byte)0xbb,(byte)0xbf};
        fileWriter.write(new String(uft8bom));
    } catch (IOException e) {
        log.error("新建文件異常:", e);
    }
    try {
        csvFilePrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withRecordSeparator(SPLIT_LINE_SEPARATOR));
    } catch (IOException e) {
        log.error("初始化csv異常:", e);
    }
}

public void close(){
    try {
        fileWriter.close();
        csvFilePrinter.close();
    } catch (IOException e) {
        log.error("關閉文件異常:", e);
    }
}

public CsvExport(List<String> headList, List<List<String>> dataList, boolean isFirst, String fileUrl) {
    this.headList = headList;
    this.dataList = dataList;
    this.isFirst = isFirst;
    this.fileUrl = fileUrl;
    init();
}

public static CsvExport getInstance(List<String> headList, List<List<String>> dataList, boolean isFirst, String fileUrl){
    return new CsvExport(headList, dataList, isFirst, fileUrl);
}

public void addList(List<List<String>> list){
    this.dataList.addAll(list);
}

public void exportCsv(){
    if (isFirst && CollectionUtils.isNotEmpty(headList)){
        try {
            csvFilePrinter.printRecord(headList);
        } catch (IOException e) {
            log.error("寫入csv頭異常:", e);
        }
        isFirst = false;
        headList = null;
    }
    if(CollectionUtils.isEmpty(dataList)){
        return ;
    }
    dataList.forEach(d -> {
        try {
            csvFilePrinter.printRecord(d);
        } catch (IOException e) {
            log.error("寫入csv數據異常:", e);
        }
    });
    dataList.clear();
    return ;
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章