Insert from CSV file to table in asp.net core

0

I have tried unsuccessfully to enter from a CSV file to my data table. So far the code I have is the following:

[HttpPost("UploadFiles")]
    public async Task<IActionResult> Post(IFormFile files)
    {

        var filePath = Path.GetTempFileName();

        if (files.Length > 0)
        {


            var st = new MemoryStream();
            await files.CopyToAsync(st);
            //files.CopyTo(st);
            var content = Encoding.UTF8.GetString(st.ToArray());                

            return Ok(content);

        }
        else
        {
            return Ok("ERROR");
        }



    }

Although it shows me the results with the return, I can not move forward to insert each record in my data table. Some help? Thank you very much already.

UPDATE

Although I was able to insert the records of the CSV file, it only does so from the second row. I tried leaving a single row and I see an exception that the format is not valid for the field to insert. (I clarify that this error does not appear when there is more than one record, insert well, but from the second row of my CSV file). I pass the code:

[HttpPost("UploadFiles")]
    public async Task<IActionResult> Post(IFormFile files, Opj opj)
    {
        //long size = files.Sum(f => f.Length);

        // full path to file in temp location
        var filePath = Path.GetTempFileName();

        if (files.Length > 0)
        {


            var st = new MemoryStream();
            await files.CopyToAsync(st);
            //files.CopyTo(st);
            var content = Encoding.UTF8.GetString(st.ToArray());
            string[] datos = content.Split("\n");

            foreach(var item in datos)
            {
                if(!string.IsNullOrEmpty(item))
                {
                    var cells = item.Split(";");
                    opj.NroOrden = Convert.ToInt32(cells[0]);
                    opj.Abogado = cells[1];
                    opj.Caratula = cells[2];
                    opj.Dni = Convert.ToInt32(cells[3]);
                    opj.Importe = Convert.ToDecimal(cells[4]);
                    opj.Juzgado = Convert.ToInt32(cells[5]);
                    opj.Liquidada = false;
                    opj.NroExpediente = Convert.ToInt32(cells[6]);
                    opj.NroFolio = Convert.ToInt32(cells[7]);
                    opj.Presentacion = Convert.ToDateTime(cells[8]);
                    opj.RetencionGan = Convert.ToDecimal(cells[9]);
                    opj.RetencionIva = Convert.ToDecimal(cells[10]);
                    _context.Opjs.Add(opj);
                }
            }
            _context.SaveChanges();

            return Ok(content);

        }
        else
        {
            return Ok("ERROR");
        }

    }

UPDATE 2

@fredyfx Place a breakpoint to see how many lines it takes me. In my example file I only have 2 rows, but I am processing 512. Obviously I am doing something wrong. The question that arises is whether this is the best way. I add image of the breakpoint:

    
asked by German W 10.08.2018 в 00:01
source

1 answer

0

@ jose-a-fernandez Well I think I could achieve it. I installed many packages, but I could not make them read the file (obviously it is due to lack of understanding).

Then I continued with C # and what I wrote is the following, which at the moment responds quite well. Some validations are missing but I tried two lines and I insert both.

            List<string> strContent = new List<string>(); //creo un List para almacenar los datos del archivo CSV

        if (files.Length > 0)
        {
            using (var stream = new StreamReader(files.OpenReadStream()))
            {
                while (!stream.EndOfStream)
                {
                    var linea = stream.ReadLine();
                    strContent.Add(linea);//agrego al List el contenido del archivo                   
                }           

                foreach(var item in strContent.Skip(1))//salteo las cabeceras
                {
                    var cells = item.Split(";");//separo por ;

                    opj.NroOrden = Convert.ToInt32(cells[0]);
                    opj.Abogado = cells[1];
                    opj.Caratula = cells[2];
                    opj.Dni = Convert.ToInt32(cells[3]);
                    opj.Importe = Convert.ToDecimal(cells[4]);
                    opj.Juzgado = Convert.ToInt32(cells[5]);
                    opj.Liquidada = false;
                    opj.NroExpediente = Convert.ToInt32(cells[6]);
                    opj.NroFolio = Convert.ToInt32(cells[7]);
                    opj.Presentacion = Convert.ToDateTime(cells[8]);
                    opj.RetencionGan = Convert.ToDecimal(cells[9]);
                    opj.RetencionIva = Convert.ToDecimal(cells[10]);

                    _context.Opjs.Add(opj);
                    _context.SaveChanges();
                }

            }
            return Ok("Éxito");//si llego aca esta todo bien

        }
        else
        {
            return Ok("ERROR");//no se cargo ningún archivo
        }

If there is someone who wants to correct and tell me if the form is correct or if it exists (I guess so) another way to make it more efficient is welcome.

Greetings.

    
answered by 14.08.2018 в 19:37