ASP.NET – Cargar Fichero a un DataGrid

Written by lopezatienza on 07/04/2009 – 16:25 -

En este ejemplo os voy a mostrar como obtener un fichero del equipo del cliente, subirlo al servidor, cargar los datos en un DataGrid y a continuación eliminar el fichero.

Necesitaremos un File Input:

<input id="File1" style="WIDTH: 350px; HEIGHT: 22px" type="file" size="39" name="File1" runat="server"/>

Además del DataGrid donde queremos insertar lo que leemos del fichero, en mi caso se llamará Datagrid, deberá tener la propiedad AutoGenerateColumns a True.

Introduciremos el código en algún evento de nuestra aplicación, por ejemplo en el evento Click de algun botón.

try
{
// PASO 1: Sube el fichero seleccionado al servidor
// Si la carpeta no existe, la crea

string Path = HttpContext.Current.Server.MapPath("");
if (!System.IO.Directory.Exists(Path + @"\NombreCarpeta"))
{
System.IO.Directory.CreateDirectory(Path + @"\NombreCarpeta");
}
string Archivo = string.Empty;
Archivo = File1.PostedFile.FileName;
Archivo = System.IO.Path.GetFileName(Archivo);

File1.PostedFile.SaveAs(Path + @"\NombreCarpeta\" + Archivo);

// FIN PASO 1

// PASO 2: Muestra los datos por pantalla

int NumeroFilas = 0;
string Lectura = "";
string texto;
DataTable _DT_ = new DataTable();
System.IO.StreamReader sr = new System.IO.StreamReader(Path + @"\NombreCarpeta\" + Archivo);

while ((texto = sr.ReadLine()) != null)
{
NumeroFilas += 1;
Lectura = Lectura + texto + "|";
}
if (Lectura.EndsWith("|"))
Lectura.Remove(Lectura.Length - 1, 1);
string[] Columna = Lectura.Split('|');
_DT_ = ArrayToDataTable(Columna, NumeroFilas);
Datagrid.PageSize=15;
Datagrid.PagerStyle.PageButtonCount=15;
Datagrid.DataSource=_DT_;
Datagrid.DataBind();

sr.Close();

// FIN PASO 2

// PASO 3: Borra el fichero subido.

System.IO.File.Delete(Path + @"\NombreCarpeta\" + Archivo);

// FIN PASO 3

}
catch {  } 

También debereis añadir la siguiente función que se encarga de pasar del tipo Array a DataTable:

public DataTable ArrayToDataTable(string[] arr, int NumeroFilas)
{
DataTable DT = new DataTable();
//string[] header = arr[0].Split(',');
int i = 0;
string str1 = arr[0];
string[] item1 = str1.Split(';');

while (i &lt; item1.Length)
{
DT.Columns.Add("Col " + i);
i++;

try
{
for (int theRow = 0; theRow &lt; NumeroFilas; theRow++)
{

string str = arr[theRow];
string[] item = str.Split(';');
DataRow dr = DT.NewRow();
if (item.Length == item1.Length)
{
for (int theColumn = 0; theColumn &lt; item.Length; theColumn++)
{
dr[theColumn] = item[theColumn];
}
DT.Rows.Add(dr);
}
else { break; }

}
}
catch { }

return DT;
} 

**Para realizar la carga correcta del fichero al DataGrid, debemos separar los campos del fichero por el carácter separador ';' y tener cada registro en cada línea del fichero.

Nombres de clase utilizadas:

using System.Collections;
using System.Data;
using System.IO;


Autor: Antonio Lopez Atienza


Tags:
Posted in ASP.NET | 1 Comment »

One Comment to “ASP.NET – Cargar Fichero a un DataGrid”

  1. KattyBlackyard Says:

    Hi, gr8 post thanks for posting. Information is useful!

Leave a Comment

 

RSS
MCC D5E