1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

csvhelperのエラー処理

Posted at

Summary

csvhelperにおけるエラー処理

script

# r "nuget: csvhelper"

open System.Globalization
open System.IO
open CsvHelper
open CsvHelper.Configuration


[<CLIMutable>]
type public Csv =
  {
    name : string
    price : int
    color : string
    memo : string
  }


[<Sealed>]
type public CsvMap () as this =
  inherit ClassMap<Csv>()
  do
    this.Map(fun x -> x.name).Index(0) |> ignore
    this.Map(fun x -> x.price).Index(1) |> ignore
    this.Map(fun x -> x.color).Index(2) |> ignore
    this.Map(fun x -> x.memo).Index(3) |> ignore


let public csvRead  (streamReader:StreamReader)  =

  let csvConfig : CsvConfiguration  =
    CsvConfiguration(CultureInfo.CurrentCulture)
    |> fun x ->
      x.Delimiter <- ","
      x.HasHeaderRecord <- true
      x.DetectColumnCountChanges <- true
      x

  use csv = new CsvReader(streamReader , csvConfig )
  csv.Context.RegisterClassMap<CsvMap>() |> ignore

  let mutable flg = true
  while flg do
    try
      flg <- (csv.Read())
      if flg
      then csv.GetRecord<Csv>() |> printfn "%A"
    with
      | :? BadDataException ->
        printfn "bad data exception!"
      | :? TypeConversion.TypeConverterException ->
        printfn "type conversion exception!"
      | _ ->
        printfn "others exeption!"


new StreamReader( "./fruits.csv"  )
|> csvRead

Csv1

name,price,color,memo
apple,300,red,solid sweet!
banana,1,980,yellow,great sweet!
cherry,520,black,very delicious!

error

{ name = "apple"
  price = 300
  color = "red"
  memo = "solid sweet!" }
bad data exception!
{ name = "cherry"
  price = 520
  color = "black"
  memo = "very delicious!" }

csv2

name,price,color,memo
apple,300,red,solid sweet!
banana,aaa,yellow,great sweet!
cherry,520,black,very delicious!

error

{ name = "apple"
  price = 300
  color = "red"
  memo = "solid sweet!" }
type conversion exception!  
{ name = "cherry"
  price = 520
  color = "black"
  memo = "very delicious!" }

現場からは以上です

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?