I do not know how to explain my problem very well. I have never known how to do it with certainty.
I will start by showing you my code where I ask the user to enter the following information: Name, last name, age and sex. These data will be saved in Excel. Keep in mind that the file already has data stored in it.
my code is as follows:
void EscribirEnExcel(string pathfile)
{
string nombre="", apellido = "", sexo = "";
char opt;
int? Edad = null;
SLDocument sL = new SLDocument(pathfile);
SLWorksheetStatistics stats = sL.GetWorksheetStatistics();
System.Data.DataTable dataTable = new System.Data.DataTable();
int row = stats.EndRowIndex;
Console.WriteLine(row);
do {
Console.WriteLine("Desea añadir más datos? Si(y) No(n) ");
opt = Convert.ToChar(Console.ReadLine());
row++;
switch (opt)
{
case 'y':
Console.WriteLine("Escriba su: nombre,apellido,edad y sexo");
nombre = Console.ReadLine();
apellido = Console.ReadLine();
Edad = Convert.ToInt32(Console.ReadLine());
sexo = Console.ReadLine();
dataTable.Columns.Add("Nombre", typeof(string));
dataTable.Columns.Add("Apellido", typeof(string));
dataTable.Columns.Add("Edad", typeof(int));
dataTable.Columns.Add("Sexo", typeof(string));
//registros
dataTable.Rows.Add(nombre, apellido, Edad, sexo);
sL.ImportDataTable(row, 1, dataTable, false);
sL.Save();
break;
case 'n':
break;
}
} while (opt != 'n') ;
}
The second time I try to enter data into the file it shows me the following error: 'The column' Name 'already belongs to DataTable.' in this part of the code
dataTable.Columns.Add("Nombre", typeof(string));
And if I remove the columns, the following error appears: 'The input matrix is longer than the number of columns in this table.' in
dataTable.Rows.Add(nombre, apellido, Edad, sexo);
How could I do it in such a way that I can enter the data without being marked by any of the errors mentioned?