0
Guys, I’m trying to generate a spreadsheet filled with the data I have from SQL server, I can get that information right but when I call a method responsible for taking that information and recording it into an Excel spreadsheet whenever the endpoint containing that method is called take null reference error(at least that’s what I got).
I tried to debug but even marking in the responsible method with breakpoint it does not even enter so I can better understand what happens inside.
Is there any other way besides breakpoint to catch what is causing this error ?
Here’s the method I call in the controller :
public class CriarExcel
{
private readonly EmployeeRepository _repository;
public CriarExcel(EmployeeRepository repository)
{
_repository = repository;
}
public string PreencherExcel()
{
try
{
ArquivoExcelEmployee arquivoExcelEmployee = new ArquivoExcelEmployee();
Console.WriteLine("Carregando configurações...");
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile($"appsettings.json");
var configuration = builder.Build();
DateTime dataHoraExtracao = DateTime.Now;
var excelConfigurations = new ExcelConfigurations();
new ConfigureFromConfigurationOptions<ExcelConfigurations>(
configuration.GetSection("ExcelConfigurations"))
.Configure(excelConfigurations);
Console.WriteLine("Gerando o arquivo .xlsx (Excel) com as cotações...");
string arquivoXlsx = arquivoExcelEmployee.GerarArquivo(
excelConfigurations, dataHoraExtracao,
_repository.Get());
Console.WriteLine($"O arquivo {arquivoXlsx} foi gerado com sucesso!");
return arquivoXlsx;
}
catch (Exception Ex)
{
throw Ex;
}
}
}
The error indicates that the _creatExcel variable is null. Are you sure this variable was initialized? If you can put the controller code it would also be easier to help.
– Talles Santana
That’s exactly what _creatExcel , I was told to research about constructor injection and I found that I had to put this _creatExcel = create Xcel and add in startup.Cs after I did it was right.
– Nicholas Souza
private readonly CriarExcel _criarExcel;
 public EmployeeController(CriarExcel criarExcel )
 {
 
 _criarExcel = criarExcel //Por _criarExcel não estar iniciada aprensentava o erro
 }
– Nicholas Souza
Thanks @Tallessantana
– Nicholas Souza
I’m glad my comment helped. You’re welcome :)
– Talles Santana
@Nicholassouza just a hint beyond what you’ve been told... Delete that Try-catch block of yours, as it is doing nothing but weigh your code more. This instruction has a high cost and in this your scenario is doing nothing. A hug!
– Pedro Paulo
Thanks @Pedropaulo didn’t know it had an impact on performance
– Nicholas Souza