I am developing a functionality that is responsible for reading an Excel document, and exporting its data to PostgreSQL. So far I have the following process. In an ASP.NET MVC application with C#, I generate a page where it is requested to enter a file.
This file is read and saved inside a stream object. Then, with the NPOI library, I convert this file into a list of entities that is created according to the data from the Excel document in read. Finally, after the list is done, it is saved via Entity Framework to the database. Here is the code that works today.
public async Task<ActionResult> Index([FromForm] IFormFile archivoExcel)
{
try
{
if (archivoExcel.Length > 0)
{
Stream excelStream = archivoExcel.OpenReadStream();
IWorkbook miExcel = null;
if (Path.GetExtension(archivoExcel.FileName) == ".xlsx")
{
miExcel = new XSSFWorkbook(excelStream);
}
else
{
miExcel = new HSSFWorkbook(excelStream);
}
List<ManifiestoExcel> lstManifiestoExcel = new List<ManifiestoExcel>();
var sheet = miExcel.GetSheetAt(0);
for (int i = 1; i < sheet.PhysicalNumberOfRows; i++)
{
var sheetRow = sheet.GetRow(i);
ManifiestoDetalle md = new ManifiestoDetalle();
md.CodigoEntrega = sheetRow.Cells[0].ToString();
md.Pais = sheetRow.Cells[1].ToString();
md.NombreCompleto = sheetRow.Cells[2].ToString();
md.CodArea = Convert.ToInt32(sheetRow.Cells[3].ToString());
md.Telefono = Convert.ToInt32(sheetRow.Cells[4].ToString());
md.Direccion1 = sheetRow.Cells[5].ToString();
md.Direccion2 = sheetRow.Cells[6].ToString();
md.Direccion3 = sheetRow.Cells[7].ToString();
md.Region = sheetRow.Cells[8].ToString();
md.Comuna = sheetRow.Cells[9].ToString();
md.CodigoPostal = Convert.ToInt32(sheetRow.Cells[10].ToString());
md.RutDni = sheetRow.Cells[11].ToString();
md.DescripcionEnvio = sheetRow.Cells[12].ToString();
md.Precio = Convert.ToInt32(sheetRow.Cells[13].ToString());
lstManifiestoExcel.Add(md);
}
await _context.SaveChangesAsync();
}
else
{
ViewBag.Message = "Empty File Upload Failed";
}
}
catch (Exception ex)
{
ViewBag.Message = "File Upload Failed";
}
return View(await _context.Manifiestos.ToListAsync());
}
This code works fine when there are few records. The problem is generated, when already in production, there are many records, since it gets stuck...
In Python, I have done tests to record in a database in Heroku, 30,000 records of this type, and the load takes less than 10 seconds. I tried to run the Python script from a .NET Core application, but I didn't have very good results, because with this method you can't use libraries like NumPy or Pandas.
Is there a way to do a bulk insert in PostgreSQL from .NET Core? I have looked for examples, but they only appear for SQL Server.