当前位置: 首页 > 工具软件 > openCSV > 使用案例 >

OpenCSV 用法总结

尹赞
2023-12-01

        最近工作中有个需求要求导出 csv格式的文件,之前碰到到类似的需求,最后在Google上找到了 OpenCSV,并且提供Java API

OpenCSV地址:https://code.google.com/p/opencsv/

网站上提供了完整的示例代码,这里只贴CSV读写示例代码,其他的请移步至官网去查看!

import java.util.Arrays;

public class CSVAfter {
        
        // define format of CSV file one time and use everywhere
        // human readable configuration 
        private static final CSV csv = CSV
                        .separator(';')
                        .quote('\'')
                        .skipLines(1)
                        .charset("UTF-8")
                        .create();

        // do not throw checked exceptions
        public static void main(String[] args) {
                String fileName = "test.csv";
                
                // CSVWriter will be closed after end of processing
                csv.write(fileName, new CSVWriteProc() {
                        public void process(CSVWriter out) {
                                out.writeNext("Header1", "Header2");
                                out.writeNext("v11", "v12");
                                out.writeNext("v21", "v22");
                        }
                });
                
                // CSVReader will be closed after end of processing
                // Less code to process CSV content -> less bugs
                csv.read(fileName, new CSVReadProc() {
                        public void procRow(int rowIndex, String... values) {
                                System.out.println(rowIndex + "# " + Arrays.asList(values));    
                        }
                });
        }
}






 类似资料: