Ver Mensaje Individual
  #2 (permalink)  
Antiguo 03/01/2011, 15:16
Avatar de Porlachucha
Porlachucha
 
Fecha de Ingreso: noviembre-2008
Ubicación: Santiago
Mensajes: 172
Antigüedad: 15 años, 6 meses
Puntos: 5
Respuesta: cargar excel a un gridview en asp.net y c#

tienes 3 formas de hacer esta tarea....

1.- Cargar usando adaptador JET... lo cual no te recomiendo a menos que asegures que los tipos de datos no van a cambiar en las filas, ya que esto provoca que el motor se confunda y formatee los datos de acuerdo a los 5 primeros registros de cada columna..
de todas formas aca te dejo un codigo con el cual puedes usar este metodo.

Código:
        public static DataTable dttLeerDatosDesdeExcel(string sNombreArchivo, string sNombreHoja, bool bTodoTexto)
        {
            try
            {
                OleDbConnection oConnXLS = new OleDbConnection();        //Crea una nueva conexion al excel
                OleDbCommand oDBCmdXLS = new OleDbCommand();             //objeto command, para excel
                OleDbDataAdapter oDBDaXLS = new OleDbDataAdapter();      //objeto dataadapter para el excel
                DataTable dttDatosXLS = new DataTable();                  //contiene TODOS los datos del Excel
                //oConnXLS.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sNombreArchivo + ";Extended Properties=\"Excel 8.0;HDR=No;IMEX=1\"";

                //string sConexionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sNombreArchivo + @;Extended Properties="Excel 8.0;HDR=No;IMEX=1";
                //oConnXLS.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sNombreArchivo + ";Extended Properties=Excel 8.0;";

                string sConexionString;
                if (bTodoTexto)
                {
                    sConexionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=";
                    sConexionString += sNombreArchivo;
                    sConexionString += ";Extended Properties=\"Excel 8.0;HDR=No;IMEX=1\"";
                }
                oConnXLS.ConnectionString = sConexionString;
                oConnXLS.Open();
                oDBCmdXLS.CommandText = "Select * From [" + sNombreHoja + "$]";
                oDBCmdXLS.Connection = oConnXLS;
                oDBDaXLS.SelectCommand = oDBCmdXLS;
                oDBDaXLS.Fill(dttDatosXLS);
                oConnXLS.Close();
                if (dttDatosXLS.Rows.Count > 0)
                {
                    return dttDatosXLS;
                }
                else
                {
                    return null;
                }
            }
            catch (System.IO.IOException Err0)
            {
                return null;
            }
        }
una segunda opcion, es utilizar Objetos COM, par alo cual debes tener instalado office (excel) en la maquina donde vas a ejecutar el programa. Toiene un inconveniente, y es que es un poco complicado eliminar las instancias de la memoria despues de terminar de usar la fiuncion... esto puede provocar por ejemplo si se instala en un server, que se vayan generando procesos que no se eliminan.. y al fiunal tienes como 1000....
El codigo es el siguiente (al final hay unos procesos que sirven para eliminar procesos de la memoria, pero no funciona muy bien)

Código:
          private System.Data.DataSet _dttXlsToDts(string _sPath, string _sHoja, System.Data.DataTable _dttFormato, string _sPassword)
        {
            dtsDataSource = new DataSet(_sPath.Substring(_sPath.LastIndexOf("\\") + 1));
            int iTime = 50;
            Microsoft.Office.Interop.Excel.Application oApp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbooks oBooks = oApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook oBook = oBooks.Add(Type.Missing);

            oBook = oApp.Workbooks.Open(_sPath,             //Source File Name
                                      0,                    //UpdateLinks
                                      false,                //ReadOnly
                                      5,                    //Format
                                      "",                   //Password
                                      "",                   //WriteResPassword
                                      true,                 //IgnoreReadOnly
                                      Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, //Origin
                                      "\t",                 //Delimiter
                                      false,                //Editable
                                      false,                //Notify
                                      0,                    //Converter
                                      false,                //AddToMru
                                      null,                 //Load
                                      null);                //CorruptLoad

            for (int i = 1; i < oBook.Worksheets.Count + 1; i++)
            {
                Microsoft.Office.Interop.Excel.Worksheet sheet = new Microsoft.Office.Interop.Excel.Worksheet();
                sheet = (Microsoft.Office.Interop.Excel.Worksheet)oBook.Worksheets.get_Item(i);
                if (sheet.Name.ToString().Trim().ToUpper() == _sHoja.Trim().ToUpper())
                {


                    System.Data.DataTable dttAux = new System.Data.DataTable();
                    dttAux = loadDataTable((Microsoft.Office.Interop.Excel.Worksheet)oBook.Worksheets.get_Item(i));
                    if (dttAux == null || dttAux.Rows.Count == 0)
                    {
                        continue;
                    }

                    // revisa si existe el datatable con el formato
                    if (_dttFormato != null && _dttFormato.Rows.Count > 0)
                    {
                        if (bFormatoOK(_dttFormato, dttAux))
                        {
                            dtsDataSource.Tables.Add(dttAux);
                        }
                    }
                }
            }
            #region Close WorkBook Method Parameters
            //NAR(hoja, iTime);
            oBook.Close(false, Type.Missing, Type.Missing);
            NAR(oBook, iTime);
            NAR(oBooks, iTime);
            oApp.Quit();
            NAR(oApp, iTime);

            if (!bKillExcellProcess(iTime))
            {
                return null;
            }
            #endregion
            return dtsDataSource;
            #endregion
        }

        public static void NAR(object o, int iTime)
        {
            try
            {
                System.Threading.Thread.Sleep(iTime);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
                System.Threading.Thread.Sleep(iTime);
            }
            catch (Exception ex)
            {
                System.Console.WriteLine("objeto cerrado [" + o.ToString().Trim() + "] Error [" + ex.ToString().Trim() + "]");
            }
            finally
            {
                o = null;
            }
        }
        public static bool bKillExcellProcess(int iTime)
        {
            // elimina procesos excel por si hubiese alguno
            try
            {
                System.Threading.Thread.Sleep(iTime);
                int idproc = GetIDProcces("EXCEL");
                while (idproc != -1)
                {
                    System.Threading.Thread.Sleep(iTime);
                    idproc = GetIDProcces("EXCEL");
                    if (idproc != -1)
                    {
                        Process.GetProcessById(idproc).Kill();
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        public static int GetIDProcces(string nameProcces)
        {
            try
            {
                Process[] asProccess = Process.GetProcessesByName(nameProcces);
                foreach (Process pProccess in asProccess)
                {
                    /*if (pProccess.MainWindowTitle.ToString().Trim().Substring(0, 14) == "Microsoft Excel")
                    {
                        return pProccess.Id;
                    }*/

                    if (pProccess.MainWindowTitle == "")
                    {
                        return pProccess.Id;
                    }
                }
                return -1;
            }
            catch (Exception ex)
            {
                return -1;
            }
        }
Una tercera opcion (que es mejor que las 2 anteriores), pero que es necesario tener instalado un prodyucto de terceros ej: aspose, devexpress, o alguna otra weba por el estilo.. este metodo es mejor, porque no tiene los problemas de los metodos anteriores.. pero requiere licencia.
aca te dejo un ejemplo con un producto que se llam aspose
Código:
        public static DataTable dttLeerDatosDesdeExcel(string sArchivo, string sHoja, DataTable dttFormatoExcel)
        {
            Aspose.Cells.License license = new Aspose.Cells.License();
            license.SetLicense("Aspose.Cells.lic");
            Workbook workbook = new Workbook();
            workbook.Open(sArchivo);
            Worksheet worksheet = workbook.Worksheets[sHoja];
            int iNumeroMaximoFilas = worksheet.Cells.MaxDataRow + 1;
            int iNumeroMaximoColumnas = worksheet.Cells.MaxDataColumn + 1;
            DataTable dttAux = worksheet.Cells.ExportDataTable(0, 0, iNumeroMaximoFilas, iNumeroMaximoColumnas, false);
            return dttAux;

        }

espero te sirva
__________________
Nada mas patetico que "detestar" a Intel o Microsoft o Windows o Apple ... apuesto que eres el tipico teton espinilluo y pajero que usa Linux para sentirse capo ...