ASP.NET - Cargar Fichero a un DataGrid

Written by lopezatienza on 7 Abril 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:

  1. <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.

  1. try
  2. {
  3. // PASO 1: Sube el fichero seleccionado al servidor
  4. // Si la carpeta no existe, la crea
  5.  
  6. string Path = HttpContext.Current.Server.MapPath("");
  7. if (!System.IO.Directory.Exists(Path + @"\NombreCarpeta"))
  8. {
  9. System.IO.Directory.CreateDirectory(Path + @"\NombreCarpeta");
  10. }
  11. string Archivo = string.Empty;
  12. Archivo = File1.PostedFile.FileName;
  13. Archivo = System.IO.Path.GetFileName(Archivo);
  14.  
  15. File1.PostedFile.SaveAs(Path + @"\NombreCarpeta\" + Archivo);
  16.  
  17. // FIN PASO 1
  18.  
  19. // PASO 2: Muestra los datos por pantalla
  20.  
  21. int NumeroFilas = 0;
  22. string Lectura = "";
  23. string texto;
  24. DataTable _DT_ = new DataTable();
  25. System.IO.StreamReader sr = new System.IO.StreamReader(Path + @"\NombreCarpeta\" + Archivo);
  26.  
  27. while ((texto = sr.ReadLine()) != null)
  28. {
  29. NumeroFilas += 1;
  30. Lectura = Lectura + texto + "|";
  31. }
  32. if (Lectura.EndsWith("|"))
  33. Lectura.Remove(Lectura.Length - 1, 1);
  34. string[] Columna = Lectura.Split('|');
  35. _DT_ = ArrayToDataTable(Columna, NumeroFilas);
  36. Datagrid.PageSize=15;
  37. Datagrid.PagerStyle.PageButtonCount=15;
  38. Datagrid.DataSource=_DT_;
  39. Datagrid.DataBind();
  40.  
  41. sr.Close();
  42.  
  43. // FIN PASO 2
  44.  
  45. // PASO 3: Borra el fichero subido.
  46.  
  47. System.IO.File.Delete(Path + @"\NombreCarpeta\" + Archivo);
  48.  
  49. // FIN PASO 3
  50.  
  51. }
  52. catch {  }

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

  1. public DataTable ArrayToDataTable(string[] arr, int NumeroFilas)
  2. {
  3. DataTable DT = new DataTable();
  4. //string[] header = arr[0].Split(',');
  5. int i = 0;
  6. string str1 = arr[0];
  7. string[] item1 = str1.Split(';');
  8.  
  9. while (i &lt; item1.Length)
  10. {
  11. DT.Columns.Add("Col " + i);
  12. i++;
  13.  
  14. try
  15. {
  16. for (int theRow = 0; theRow &lt; NumeroFilas; theRow++)
  17. {
  18.  
  19. string str = arr[theRow];
  20. string[] item = str.Split(';');
  21. DataRow dr = DT.NewRow();
  22. if (item.Length == item1.Length)
  23. {
  24. for (int theColumn = 0; theColumn &lt; item.Length; theColumn++)
  25. {
  26. dr[theColumn] = item[theColumn];
  27. }
  28. DT.Rows.Add(dr);
  29. }
  30. else { break; }
  31.  
  32. }
  33. }
  34. catch { }
  35.  
  36. return DT;
  37. }

**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;


Tags:
Posted in ASP.NET |

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