2
I need to load two worksheets to generate a dictionary with the worksheet data.
I’m a little confused about this.. I created a Lerfile method to not repeat the code, since the process is the same for both files. This method returns a dictionary with the data.
public object LerPlanilha(string range, FileInfo planilha)
{
using (var pck = new ExcelPackage(planilha))
{
var worksheet = pck.Workbook.Worksheets[1];
var cells = worksheet.Cells;
var dictionary = cells[range]
.GroupBy(c => new { c.Start.Row, c.Start.Column })
.ToDictionary(
rcg => new KeyValuePair<int, int>(rcg.Key.Row, rcg.Key.Column),
rcg => cells[rcg.Key.Row, rcg.Key.Column].Value);
return dictionary;
}
}
I need to call twice on two different buttons, to load the data of a spreadsheet at a time, in btnModel I assign the return of Lerfile in the global variable Cellulareascodel that is an Object. I’m doing it this way
private void btnModelo_Click(object sender, EventArgs e)
{
var arquivo = CarregarArquivo().ToString();
if (arquivo != "OK")
{
var planilhaBase = new FileInfo(arquivo);
CelulasCarregadasModelo = LerPlanilha("B16:AG16", planilhaBase);
lblModeloCarregado.Visible = true;
lblModeloNome.Visible = true;
lblModeloCarregado.Text = "Planilha Carregada";
lblModeloNome.Text = Path.GetFileNameWithoutExtension(arquivo);
}
else
{
lblModeloCarregado.Visible = true;
lblModeloCarregado.Text = "Erro/Modelo não selecionado";
}
}
And in the other btnPlan button I assign the return of Readfile in Cellulascareadaasplan
private void btnPlan_Click(object sender, EventArgs e)
{
var arquivo = CarregarArquivo().ToString();
if (arquivo != "OK")
{
var planilhaBase = new FileInfo(arquivo);
CelulasCarregadasPlan = LerPlanilha("B16:AG16", planilhaBase);
lblFluxoIntCarregado.Visible = true;
lblFluxoIntNome.Visible = true;
lblFluxoIntCarregado.Text = "Planilha Carregada";
lblFluxoIntNome.Text = Path.GetFileNameWithoutExtension(arquivo);
}
else
{
lblFluxoIntCarregado.Visible = true;
lblFluxoIntCarregado.Text = "Erro/Modelo não selecionado";
}
}
Everything happens smoothly, the variable is filled with the dictionary.
What happens is that the variables are cleaned after the end of the button method, I cannot leave them loaded and then compare the two dictionaries in another method.
Dude, just declare the variables out of the methods.
– Jéf Bueno
@jbueno But the variables Cellulascarregadasmodel and Cellulascarregadasplan are not being declared within the method. I declare them after public form1()
– Gabriel Bernardone
Then there is something wrong with your code or your explanation. When do variables lose their value? How do you know they had value at some point?
– Jéf Bueno
Since you are using web Forms, I believe your problem is the postback, each button makes a postback right? If so, you will have to persist this variable somewhere to recover in the second postback, be it session, viewsate or context.
– André Luis Marmo
It’s web or desktop?
– Aline