[]
        
(Showing Draft Content)

Import CSV File with Custom Parser

GcExcel .NET 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 GcExcel.

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 to Parser property of the csvOpenOptions class to get the expected results on importing the CSV file.

// Create CsvOpenOptions and custom parser rules.
CsvOpenOptions csvOpenOptions = new CsvOpenOptions();
csvOpenOptions.Parser = new CustomParser();
        
// Open csv file with option.
workbook.Open(fileStream, csvOpenOptions);
public class CustomParser : ICsvParser
{
    public void Parse(CsvParseResult csvParseResult, CsvParseContext context)
    {
        if (context.Text.StartsWith("00"))
        {
            csvParseResult.Value = context.Text;
        }
        else if (context.Column == 5 || context.Column == 6)
        {
            csvParseResult.NumberFormat = "#.00";
        }
        else if (csvParseResult.NumberFormat.Equals("m/d/yyyy h:mm"))
        {
            csvParseResult.NumberFormat = "m/d/yyyy";
        }
    }
}