Document Solutions for Excel, Java Edition | Document Solutions
File Operations / Import CSV File with Custom Parser
In This Topic
    Import CSV File with Custom Parser
    In This Topic

    DsExcel Java allows you to import CSV files using custom parsing rules to get results in a specific format. For instance, a cell with numeric type data is automatically parsed as a numeric cell. However, in some cases you want to load it as a string. In such cases, you can use this feature to define your own rules when you do not get the desired result with default parser settings of DsExcel.

    You can import CSV files with customized parsing rules by implementing ICsvParser interface to define custom parsing rules using the Parse method. The method accepts objects of CsvParseResult and CsvParseContext class as parameters. As CsvParseResult class represents the parsed text, you can pass the result generated by custom parsing rules to the CsvParseResult object and specify the location and text information of the target cell through the CsvParseContext class. Once the ICsvParser interface is implemented, pass it as the argument of the setParser method of the CsvOpenOptions class to get the expected results on importing the CSV file.

    Java
    Copy Code
    // Create CsvOpenOptions and custom parser rules.
    CsvOpenOptions csvOpenOptions = new CsvOpenOptions();
    csvOpenOptions.setParser(new CustomParser());
    
    // Open csv file with option.
    workbook.open(fileStream, csvOpenOptions);

     

    Custom Parser
    Copy Code
    public class CustomParser implements ICsvParser {
        @Override
        public void Parse(CsvParseResult csvParseResult, CsvParseContext csvParseContext) {
            if (csvParseContext.getText().startsWith("00")) {
                csvParseResult.setValue(csvParseContext.getText());
            }
            else if(csvParseResult.getNumberFormat().equals("m/d/yyyy h:mm")){
                csvParseResult.setNumberFormat("m/d/yyyy");
            }
        }
    }