Excel, leer la celda A1

Fecha: 18/Mar/2005 (12 de Marzo de 2005)
Autor: Onésimo Mustelier Castillo y onesimo@gtm.desoft.cu

 


Introducción

A muchos desarrolladores se les ha presentado la necesidad de crear reportes con ciertos estilos, provenientes de herramientas de terceros; por lo regular a los ejecutivos les gusta la forma en que se presentan los informes en formato de Microsoft Office Excel y muchas veces se nos solicita exportar a esta aplicación informes generados por sistemas de gestión, para ajustarlos a sus necesidades y gustos. Con este artículo pretendo mostrar una forma sencilla de leer una base de datos y generar un informe directamente en Excel, aprovechando todas las funcionalidades de esta herramienta; se podría decir que más del 50 por ciento de las computadoras de oficina cuentan con alguna versión de Microsoft Office, así que estimo que le será de gran utilidad a algún lector.

Comencemos

Creamos una nueva solución en Visual Studio .NET y agregamos una referencia a la librería de objeto de Excel que se encuentra en la paleta COM de la ventana de Agregar Referencias en Visual Studio .NET (Ver Figura 1).

Figura 1.

Si la versión de Office con la que cuentan es la 2000, la librería sería Microsoft Excel 11.0 Object Library; luego hacemos clic en Seleccionar y luego en Aceptar y listo.

Creamos una forma que será nuestra plataforma de lanzamiento desde donde saldrán los ejemplos que crearemos; nuestra forma se verá como muestra la Figura 2:

Figura 2.

A continuación sigue código en Visual Basic (o C# o C++.NET):

using System;
using System.Drawing;
using System.Reflection;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace WindowsApplication1
{
    /// <summary>
    /// Descripción breve de Form1.
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Label label1;
        /// <summary>
        /// Variable del diseñador requerida.
        /// </summary>
        private System.ComponentModel.Container components = null;
        public Form1()
        {
            //
            // Necesario para admitir el Diseñador de Windows Forms
            //
            InitializeComponent();
            //
            // TODO: agregar código de constructor después de llamar a InitializeComponent
            //
        }
        /// <summary>
        /// Limpiar los recursos que se estén utilizando.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }
        #region Código generado por el Diseñador de Windows Forms
        /// <summary>
        /// Método necesario para admitir el Diseñador. No se puede modificar
        /// el contenido del método con el editor de código.
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(88, 96);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(112, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "Leer La celda A1";
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(96, 152);
            this.label1.Name = "label1";
            this.label1.TabIndex = 1;
            this.label1.Text = "label1";
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Excel .NET";
            this.ResumeLayout(false);
        }
        #endregion
        /// <summary>
        /// Punto de entrada principal de la aplicación.
        /// </summary>
        [STAThread]
        static void Main() 
        {
            Application.Run(new Form1());
        }
        private void button1_Click(object sender, System.EventArgs e)
        {
            Excel._Application xlApp; 
            Excel._Workbook xlLibro; 
            Excel._Worksheet xlHoja1; 
            Excel.Sheets xlHojas ;
            string fileName = "c:\\temp\\harina.xls";
            xlApp = new Excel.Application(); 
            xlApp.Visible = true; 
            xlLibro = xlApp.Workbooks.Open(fileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value , Missing.Value , Missing.Value ); 
            xlHojas = xlLibro.Sheets ; 
            xlHoja1 = (Excel._Worksheet)xlHojas["Hoja1"]; 
            string val1 = (string) xlHoja1.get_Range ("A1",Missing.Value ).Text;
            label1.Text= val1; 
            xlLibro.Close (false, Missing.Value, Missing.Value );
            xlApp.Quit();
        }
    }
}

 


ir al índice