top of page

Leer celdas de varios archivos de excel especificados en un directorio

Código para leer información de varios archivos de EXCEL con C#.

El código es el siguiente.

Referencia necesaria 
Microsoft excel 14.0 Object Library

using System;
using System.IO;
using Microsoft.Office.Interop.Excel;

namespace ResumenDeMacros
{
    class LeerArchivoExcel
    {
        void LeerVariosArchivosExcel()
        { 

            //******NOTA TODOS LOS DOCUMENTOS EN LA RUTA DEBEN DE SER ARCHIVOS DE EXCEL****
            string ruta = @"D:\Visual\PROYECTOS C#";
            Application exlApp = new Application();
            Workbook libroExcel;
            Worksheet hojaExcel;
            Range miRango;

            try
            {
               
DirectoryInfo di = new DirectoryInfo(ruta);              

                //LEER CADA ARCHIVO EN LA RUTA ESPECIFICADA
                foreach (var fi in di.GetFiles())
                {                    
                   
libroExcel = exlApp.Workbooks.Open(ruta + @"\" + fi);

                    //Definimos la hoja a utilizar
                    hojaExcel = (Worksheet)libroExcel.Worksheets.get_Item("Mi hoja excel");        
                    try
                    {
                       
int fila = 3;
                        int columna = 5;
                        string val1 = "";
                        miRango = hojaExcel.UsedRange;
                        string DATO = (string)(miRango.Cells[fila, columna] as Range).Value2;

                        if (DATO!=null)
                        {
                       
    val1 = "El contenido de la celda es " + DATO;
                        }
                        else
                        {
                   
        val1 = "LA CELDA ESTA VACIA";
                        }
                       
System.Windows.Forms.MessageBox.Show(val1.ToString());
                    }
                    catch (Exception e)
                    {  
                       
System.Windows.Forms.MessageBox.Show("Error" + e.Message);
                    }
                    finally
                    {
                       
// cerrar
                        libroExcel.Close(false);
                        exlApp.Quit();

                    }
                }    
            }
            catch (Exception e)
            {
           
    System.Windows.Forms.MessageBox.Show("Error " + e.Message);
            }
        }

    }
}

 

bottom of page