Create a list and insert the spreadsheet data into the database when importing

I have a method protected void importar_Click(object sender, EventArgs e) and inside it I check if the file has been selected, and validate the file extension. This system is a file import system of a spreadsheet in excel, which saves the data of the spreadsheet in the bank, however, when I import the file, it takes too long, instead of working on the code with disk, Bank and memory.

I was thinking of making a list with an insert, then I would only work with the memory and the bank. There is a code that I can do this process even to customize the time? And I would like to know if there is the possibility on top of my code, use the windows service to not overload and slow down at the time of transmission of the import of my file.

protected void importar_Click(object sender, EventArgs e)
{         
//Verifica se um arquivo foi selecionado
if (selecionarArquivo.HasFile)
{
//Valida a extensão do arquivo:
if (Path.GetExtension(selecionarArquivo.FileName) != ".xlsx" && Path.GetExtension(selecionarArquivo.FileName) != ".xls")
ClientScript.RegisterStartupScript(typeof(string), "Erro", "<script>alert('Somente arquivos em excel')</script>");

else
{
if (selecionarArquivo.FileContent != null)
{
string Excel = AppDomain.CurrentDomain.BaseDirectory + selecionarArquivo.FileName;
selecionarArquivo.SaveAs(Excel);
DataTable Dados = DadosExcel(Excel);
DataSet ds = new DataSet();

ds.Tables.Add(Dados);

if (ds.Tables.Count > 0)
{
bool layoutValido = VerificaLayout(ds);
if (!layoutValido)
ClientScript.RegisterStartupScript(typeof(string), "Erro", "<script>alert('Layout do arquivo fora do padrão definido para importação.')</script>");
else
{
//Inicio da validação dos dados inseridos na planilha
int numLinhas = ds.Tables[0].Rows.Count;
//Validação básica necessária para importação. PS: NumLinhas-1 porque o arquivo tem a última linha com total, que é inútil à importação.
VerificacaoPreliminar((numLinhas - 1), ds);



//Inicio da rotina de repetição para leitura de todas as linhas, iniciando na célula B6
if (!arquivoInvalidado)
{

                                    //ClientScript.RegisterStartupScript(Page.GetType(), "Carregando...", "<script>document.getElementById('progresso').style.width = '30%';</script>");
//Verifica se existe mais de 1 interessado com mesmo CPF cadastrado, salva os interessados inexistentes e altera os cadastros q tem interessados duplicados.
this.ValidaDuplicidadeInteressado();

for (int i = 5; i < (numLinhas - 1); i++)
{
List<Processo> listaProcessoExistente = new List<Processo>();
Processo processo = null;
Interessado interessado = new Interessado();      

                                        //busca o processo pelo nº judicial anterior ou atual
if (!ds.Tables[0].Rows[i].ItemArray[1].ToString().Equals(""))
processo = aplProcesso.consultarPorNProcessoER(ds.Tables[0].Rows[i].ItemArray[1].ToString());
if (processo == null)
{
if (!ds.Tables[0].Rows[i].ItemArray[2].ToString().Equals(""))
processo = aplProcesso.consultarPorNProcessoER(ds.Tables[0].Rows[i].ItemArray[2].ToString());
}
                                        //busca o interessado por cpf/cnpj
                                        if (ds.Tables[0].Rows[i].ItemArray[7].ToString().Length == 14)
   interessado = aplInteressado.ConsultarPorCPF(AuxiliarCPF_CNPJ.DesformataCPF(ds.Tables[0].Rows[i].ItemArray[7].ToString()));
                                        if (ds.Tables[0].Rows[i].ItemArray[7].ToString().Length == 18)
                                            interessado = aplInteressado.ConsultarPorCPF(AuxiliarCPF_CNPJ.DesformataCNPJ(ds.Tables[0].Rows[i].ItemArray[7].ToString()));
if (processo != null)
{  
                                            //se o processo não for nulo busco todos procinter relacionados a ele
                                            List<ProcessoInteressado> listaprocinter = aplProcessoInteressado.consultarPorIdProcesso(processo.Codigo);
                                            if(listaprocinter.Exists(o=>o.Interessado == interessado))
                                                log.Append("O interessado informado na linha " + (i + 1) + " foi adicionado novamente ao processo " + processo.NumProcessoJudicial + " <br>");
                                            //foreach(var item in listaprocinter)
                                            //{
                                            //    if (item.Interessado == interessado)
                                            //        log.Append("O interessado informado na linha " + (i + 1) + " foi adicionado novamente ao processo " + processo.NumProcessoJudicial + " <br>");                                                 
                                            //}
                                            setProcInter(processo, interessado, ds, i);                                                                               
}
else
{
//Novo Processo - 6.3
processo = new Processo();

processo.Interessado = interessado;

processo.NumProcessoJudicial = ds.Tables[0].Rows[i].ItemArray[2].ToString().Trim();
processo.RenunciaCredito = "N";
processo.Situacao = new AplSituacao().ConsultarPorId(1);
processo.HonorarioDativo = "S";
processo.Reclamado = new AplReclamado().buscaItem(2);
processo.TipoDocumento = new AplTipoDocumento().buscaItem(4);
processo.TipoProcesso = "O";
if (ds.Tables[0].Rows[i].ItemArray[5].ToString().Contains("juizado"))
processo.Tribunal = new AplTribunal().buscaItem(71);
else
processo.Tribunal = new AplTribunal().buscaItem(3);
processo.NaturezaDespeza = new AplNaturezadeDespesa().buscaItem(3);

                                            VaraExecucao vara = new VaraExecucao();
                                            if (!ds.Tables[0].Rows[i].ItemArray[3].ToString().Equals("") && !ds.Tables[0].Rows[i].ItemArray[5].ToString().Equals(""))
                                            {
                                                List<VaraExecucao> listaVaraComarca = aplVaraExecucao.ConsultarPorNomeVaraNomeComarca(ds.Tables[0].Rows[i].ItemArray[5].ToString().Trim(), ds.Tables[0].Rows[i].ItemArray[3].ToString().Trim());
                                                if (listaVaraComarca.Count != 0)
                                                {

                                                    if (ds.Tables[0].Rows[i].ItemArray[4].ToString().Equals(""))
                                                    {
                                                        vara = listaVaraComarca.Find(o => o.NumeroVara == null);
                                                    }
                                                    else
                                                    {
                                                        vara = listaVaraComarca.Find(o => o.NumeroVara == int.Parse(ds.Tables[0].Rows[i].ItemArray[4].ToString().Trim()));
                                                    }
                                                }
                                            }
                                            if (vara != null && vara.Codigo != 0)
                                            {
                                                processo.VaraExecucao = vara;
                                            }
                                            aplProcesso.gravar(processo);
aplLog.LogarAtividade(aplUsuario.buscaPorLogin(ObterUsuarioAutenticado().Login), "Importação do processo de número judicial: " + processo.NumProcessoJudicial
+ ". Interessado: " + processo.Interessado.Nome + " - " + processo.Interessado.CPF_CNPJ + ". Tribunal "
+ processo.Tribunal.NomeTribunal + ".", DateTime.Now);
//log.Append("O processo " + processo.NumProcessoJudicial + " informado na linha " + (i + 1) + " foi cadastrado com sucesso. <br>");

setProcInter(processo, interessado, ds, i);
}
}//Fim For
                                    //ClientScript.RegisterStartupScript(typeof(string), "Carregando...", "<script>$('#progressbar').progressbar({value: 70});</script>");
                                    ClientScript.RegisterStartupScript(Page.GetType(), "Carregando...", "<script>document.getElementById('progresso').style.width = '60%';</script>");

if (listaGravarProcInter.Count != 0)
{
foreach (ProcessoInteressado item in listaGravarProcInter)
{
aplProcessoInteressado.salvar(item);
}
}
if (listaLogsAuditoria.Count != 0)
{
foreach (var item in listaLogsAuditoria)
{
aplLog.LogarAtividade(aplUsuario.buscaPorLogin(ObterUsuarioAutenticado().Login), item, DateTime.Now);
}
}
logimportacao.Visible = true;
loglbl.Text = log.ToString();
                                    //ClientScript.RegisterStartupScript(Page.GetType(), "Carregando...", "<script>document.getElementById('progresso').style.width = '100%';</script>");
ClientScript.RegisterStartupScript(typeof(string), "Alerta", "<script>alert('Arquivo importado com sucesso. Verifique o log na tela. ')</script>");
}
else
{
logimportacao.Visible = true;
loglbl.Text = log.ToString();
ClientScript.RegisterStartupScript(typeof(string), "Erro", "<script>alert('Arquivo não importado. Verifique o log de erros na tela. ')</script>");
}

}
}
}
}
}
}
Author: Amaral, 2018-02-09

1 answers

Face Datatable consumes a lot of memory resource, you can create a class only with the properties of the file you want to weigh in the bank, and use a list to store the type of your class, and in the Access part to the bank can use both ADO which is the fastest in the matter of access to data, and Dapper which is a]} Example of the class with the properties:

 public class Arquivo
{
    public int IdArquvio { get; set; }
    public string Nome { get; set; }
    public string Email { get; set; }
}

Example of the typed list:

List<Arquivo> listaArquivo = new List<Arquivo>();

I put here in a way well summarized but if you do not understand just warn that I improve!

 0
Author: Jhonatas Silva, 2018-02-09 16:14:23