Importar y exportar registros de Excel con c#

    En este articulo, vamos aprender  a realizar registro masivo  con Excel  usando  C#, cuando se hace el desarrollo de un sistema de registro, es habitual que el cliente te pida importar o exportar  registros de un archivo de Excel. En este artículo eso es lo que vamos hacer.

    Para importar y exportar registros masivos con Excel vamos usar, visual estudio 2013, SqlServer, postgreSQL y MySQL que  habitualmente se usa para el desarrollo de sistemas, a un que existe un gran cantidad de base datos  de la cual pero tu podrás adaptar al sistema que estés desarrollando, y  por supuesto un ejemplo de archivo de Excel con registros.

    También vamos utilizar librerías que nos permita manipular Excel, en el mercado existen varias librerías de pago, pero en este artículo vamos utilizar librerías de código abierto.

    1. EPPlus 4.5, soporta archivos Excel (2007-2013) con extensión .xlsx
    2. ExcelDataReader 3.7, soporta archivos Excel (97-2003) con extensión .xls.  

    Pero antes que nada  en el primer paso vamos preparar la estructura de la tabla conforme al formato del archivo Excel, para la base datos, he aquí el ejemplo.

    
    /*Estructura de tabla POSTGRESQL*/
    CREATE TABLE public.ope_transferencia(
    	opt_idtransfe serial,-- Id Auto incremental
    	opt_docidentidad numeric(8),
    	opt_nombres varchar,
    	opt_appaterno varchar,
    	opt_materno   varchar null,
    	opt_importe   numeric(20,2),
    	opt_cuentaban  varchar,
    	opt_insbanaria  varchar
    );
    
    /*Estructura de tabla MYSQL*/
    CREATE TABLE ope_transferencia(
       opt_idtransfe INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY,-- Id Auto incremental
    	opt_docidentidad numeric(8),
    	opt_nombres VARCHAR(20),
    	opt_appaterno VARCHAR(20),
    	opt_materno   VARCHAR(20) null,
    	opt_importe   numeric(20,2),
    	opt_cuentaban  VARCHAR(20),
    	opt_insbancaria  VARCHAR(30)
    );
    /*Estructura de la tabla SQLServer*/
    CREATE TABLE ope_transferencia(
    	opt_idtransfe int not null identity (1,1) primary key,
    	opt_docidentidad numeric(8),
    	opt_nombres varchar(20),
    	opt_appaterno varchar(20),
    	opt_materno   varchar(20) null,
    	opt_importe   numeric(20,2),
    	opt_cuentaban  varchar(30),
    	opt_insbanaria  varchar(30)
    );
    
    

    Una vez creado la estructura  de las tablas, vamos a proceder a crear las funciones  o procedimiento almacenado  para la inserción y otros  que nos permitirá programar la lógica. Para la creación de funciones en MySQL y PostgreSQL es mínima la diferencia, excepto en SQLServer que vamos crear procedimiento almacenado para insertar datos.   

    En el siguiente ejemplo se crea la función para insertar datos en MySQL.

    
    CREATE OR REPLACE FUNCTION f_set_transferencia(
     parametro varchar(40),
     idtrans   int(40),
     docidentidad numeric(10),
     nombre    varchar(40),
     appaterno varchar(40),
     apmaterno varchar(40),
     importe   decimal(20,2),
     cuentaban  varchar(20),
     instubban  varchar(30)
     )RETURNS VARCHAR(70)
     BEGIN
         DECLARE existreg int(40);
         DECLARE msg varchar(70);
         IF parametro='REGISTRAR' THEN
         SELECT COUNT(opt_idtransfe) into existreg  FROM ope_transferencia WHERE opt_idtransfe=docidentidad;
          IF existreg is null THEN
              INSERT INTO ope_transferencia(opt_docidentidad,opt_nombres,opt_appaterno,opt_materno,opt_importe,opt_cuentaban,opt_insbancaria) 
              VALUES(docidentidad,nombre,appaterno,apmaterno,importe,cuentaban,instubban);
              SET msg='{"success":true,"message":"Registro guardado correctamente"}';
          ELSE
             SET msg='{"success":false,"message":"Ya existe el registro"}';
        END IF;
     END IF;
        RETURN msg;
     END;
    
    

    Se muestra el código de ejecución de la función en MySQL.

    
    SELECT f_set_transferencia('REGISTRAR',NULL,'6845316', 'Rolando','Quisberth','Moncada', '6837','10000689','Visa');
    
    

    Código de procedimiento almacenado para insertar y verificar registro, ya que en SQLServer las funciones no pueden realizar cambios. He aquí el ejemplo del procedimiento almacenado.

    
    create PROCEDURE dbo.set_transferencia_pro
       @param       varchar(40),
       @idtrans      int,
       @docidentidad numeric(10),
       @nombre       varchar(40),
       @appaterno    varchar(40),
       @apmaterno    varchar(40),
       @importe      decimal(20,2),
       @cuentaban    varchar(20),
       @instubban    varchar(30)
    as
    BEGIN
     DECLARE @existreg int, @msg nvarchar(70)
      IF @param='REGISTRO' 
         BEGIN
      IF not exists (SELECT * FROM dbo.ope_transferencia WHERE dbo.ope_transferencia.opt_docidentidad=@docidentidad)
        BEGIN
          INSERT INTO dbo.ope_transferencia(opt_docidentidad,opt_nombres,opt_appaterno,opt_materno,opt_importe,opt_cuentaban,opt_insbanaria) VALUES(@docidentidad,@nombre,@appaterno,@apmaterno,@importe,@cuentaban,@instubban);
    	  RETURN 1
    	END
       ELSE
    	 BEGIN
    	  RETURN 2
    	END
       END
       ELSE
       BEGIN
       RETURN 0
       END
    END
    
    

    He aquí ejemplo de código se muestra la ejecución del procedimiento almacenado.

    
    DECLARE @return_status INT;
    DECLARE @msg_c nvarchar(70);
    EXEC @return_status =dbo.set_transferencia_pro 'REGISTRO',null,'6845316', 'Rolando','Quisberth','Moncada', '6837','10000689','Visa' 
    IF @return_status=1
     BEGIN
       SET @msg_c='{"success":true,"message":"Registro guardado correctamente"}'
     END
     ELSE
     BEGIN
       SET @msg_c='{"success":false,"message":"Ya existe registro"}'
     END
    SELECT @msg_c
    
    

    Ejemplo de código función para insertar datos en PostGreSQL.

    
    CREATE OR REPLACE FUNCTION "public".f_set_transferencia(
     parametro    varchar,
     idtrans      int,
     docidentidad numeric(10),
     nombre       varchar,
     appaterno    varchar,
     apmaterno    varchar,
     importe      decimal(20,2),
     cuentaban    varchar,
     instubban    varchar
    )RETURNS TEXT
    AS 
    $body$
    DECLARE
    existreg INTEGER;
    msg TEXT;
    BEGIN
    
         SELECT COUNT(opt_idtransfe) into existreg  FROM "public".ope_transferencia WHERE opt_docidentidad=docidentidad;
    		 IF existreg=0 THEN
    		       INSERT INTO ope_transferencia(opt_docidentidad,opt_nombres,opt_appaterno,opt_materno,opt_importe,opt_cuentaban,opt_insbanaria) 
               VALUES(docidentidad,nombre,appaterno,apmaterno,importe,cuentaban,instubban);
    					 msg='{"success":true,"message":"Registro guardado correctamente"}';
    		 ELSE
    		       msg='{"success":false,"message":"Ya existe el registro"}';
    		 END IF;
    		 RETURN msg;
    END
    $body$
    LANGUAGE 'plpgsql'
    
    

    Código para ejecutar la función.

    
    SELECT public.f_set_transferencia('Programer',null,6845316,'Rolando','Quisberth','Moncada',6837,'10000689','Visa'); 
    
    

    Formulario principal

    Una vez que tengamos listo nuestras funciones o procedimiento almacenado para importar y exportar registros de Excel, voy explicar en los siguientes fragmentos de código en C#.

    Probablemente digas bla bla que no les gusta leer mucho para eso simplemente descarga el código fuente que está en la parte de debajo de este artículo, para que puedas adaptar a tu sistema.

    Entonces vamos crear el proyecto en visual estudio, des pues de crear el proyecto vamos diseñar dos formularios, el primero formulario tendrá un botones y una grilla para visualizar datos. Tal como se muestra en la siguiente figura.

    A continuación se muestra el código  del formulario principal.

    
    using OfficeOpenXml;
    using OfficeOpenXml.Style;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace ImportExportExcel
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                this.btnimport.Click += btnimport_Click;
                this.Load += Form1_Load;
                this.btneditar.Click += Btneditar_Click;
                this.btnexport.Click += Btnexport_Click;
            }
            /// 
            /// Exporta resgistros cargados en la grilla al archivo excel
            /// y se da formato. 
            /// 
            /// 
            /// 
            private void Btnexport_Click(object sender, EventArgs e)
            {
                frmregistrar Exportar = new frmregistrar();
                var List = Exportar.Datos(ListaTrans);
                var selectdata =
                        from cust in List
                        select new { 
                            id = cust.Id, 
                            doc=cust.DocIdentidad,
                            nombre = cust.Nombre,
                            apaterno=cust.ApellidoPaterno,
                            apmaterno=cust.ApellidoMaterno,
                            importe=cust.Importe,
                            cuenta=cust.CuentaBancaria,
                            instfin=cust.InstitucionBancaria
        
                          };
                ExcelPackage excel = new ExcelPackage();
    
                var workSheet = excel.Workbook.Worksheets.Add("Export");
                workSheet.TabColor = System.Drawing.Color.Black;
                workSheet.DefaultRowHeight = 12;
                workSheet.Row(1).Height = 20;
                workSheet.Row(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                workSheet.Row(1).Style.Font.Bold = true;
                workSheet.Cells[1, 1].Value = "Id";
                workSheet.Cells[1, 2].Value = "Doc. Identidad";
                workSheet.Cells[1, 3].Value = "Nombre";
                workSheet.Cells[1, 4].Value = "Apellido paterno";
                workSheet.Cells[1, 5].Value = "Apellido materno";
                workSheet.Cells[1, 6].Value = "Importe";
                workSheet.Cells[1, 7].Value = "Cuenta bancaria";
                workSheet.Cells[1, 8].Value = "Instución financiera";
                workSheet.Cells["A1:H1"].Style.Fill.PatternType = ExcelFillStyle.Solid;
                workSheet.Cells["A1:H1"].Style.Fill.BackgroundColor.SetColor(ColorTranslator.FromHtml("#057fe9"));
                workSheet.Cells["A1:H1"].AutoFitColumns();
                workSheet.Cells["A2"].LoadFromCollection(selectdata);
                SaveFileDialog Dialogo = new SaveFileDialog();
                Dialogo.Filter = "Archivo Excel|*.xlsx";
                if (Dialogo.ShowDialog() == DialogResult.OK) {
                    string rutaFile = Dialogo.FileName; ;
                    FileStream objFileStrm = File.Create(rutaFile);
                    objFileStrm.Close();
                    File.WriteAllBytes(rutaFile, excel.GetAsByteArray());
                    excel.Dispose();
                }
            }
            /// 
            /// Recuperamos los datos de la grilla para editarlo
            /// 
            /// 
            /// 
            private void Btneditar_Click(object sender, EventArgs e)
            {
               
                frmregistrar Editar = new frmregistrar();
                Editar.Text = "Editar";
                if (datagridtransfe.Rows.Count > 0) {
    
                    int Index = datagridtransfe.CurrentRow.Index;
                    Editar.Id = Convert.ToInt32(datagridtransfe.Rows[Index].Cells["opt_idtransfe"].Value.ToString());
                    Editar.DocIdentidad = Convert.ToDecimal(datagridtransfe.Rows[Index].Cells["opt_docidentidad"].Value.ToString());
                    Editar.Nombre = datagridtransfe.Rows[Index].Cells["opt_nombres"].Value.ToString();
                    Editar.ApellidoPaterno = datagridtransfe.Rows[Index].Cells["opt_appaterno"].Value.ToString();
                    Editar.ApellidoMaterno = datagridtransfe.Rows[Index].Cells["opt_materno"].Value.ToString();
                    Editar.Importe = Convert.ToDecimal(datagridtransfe.Rows[Index].Cells["opt_importe"].Value.ToString());
                    Editar.CuentaBancaria = datagridtransfe.Rows[Index].Cells["opt_cuentaban"].Value.ToString();
                    Editar.InstitucionBancaria = datagridtransfe.Rows[Index].Cells["opt_insbanaria"].Value.ToString();
                    Editar.ShowDialog();
                    CargarRegistro();
                }
                
            }
            /// 
            /// Se carga el registros
            /// 
            /// 
            /// 
            void Form1_Load(object sender, EventArgs e)
            {
                CargarRegistro();
            }
    
            DataTable ListaTrans = new DataTable();
            /// 
            /// Cargamos registros desde la base datos
            /// 
            private void CargarRegistro() {
                ConexionDB Registrar = new ConexionDB();
                string Query = @"SELECT * FROM ope_transferencia";
                string JsonReturn = Registrar.ConexionSQL(ConexionDB.Servidores.Sqlserver, Query);
                if (!Nullable.Equals(Registrar.TablaRegistro, null))
                {
                    ListaTrans = Registrar.TablaRegistro;
                    datagridtransfe.DataSource = ListaTrans;
                }
                else {
                    MessageBox.Show("No existe registros");
                }
                
            }
            /// 
            /// Abrir formulario de proceso de importación
            /// 
            /// 
            /// 
            void btnimport_Click(object sender, EventArgs e)
            {
                frmImportExecel Importar = new frmImportExecel();
                Importar.ShowDialog();
                CargarRegistro();
            }
            /// 
            /// Abre formulario de inserción y edición de datos
            /// 
            /// 
            /// 
            private void btnnuevo_Click(object sender, EventArgs e)
            {
                frmregistrar Nuevo = new frmregistrar();
                Nuevo.ShowDialog();
                CargarRegistro();
            }
    
        }
    }
    
    

    Formulario par importar y exportar registros de Excel con c#

    En el segundo formulario tendrá  la interfaz gráfica de importación de archivo Excel, en este formulario se realizar el proceso de registro masivo, en el ejemplo se utiliza la conexión con SQLServer, para establecer con otros servidores de bases de datos simplemente cambie la cadena de conexión y el servidor de base de datos a la que conectará.

    A continuación se muestra el código del formulario de importación  de datos.

    
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Threading;
    using System.IO;
    using OfficeOpenXml;
    using System.Resources;
    using System.Web.Script.Serialization;
    using System.Text.RegularExpressions;
    using System.Globalization;
    using ImportExportExcel.Properties;
    using ExcelDataReader;
    //using MySql.Data.MySqlClient;
    using System.Data.SqlClient;
    namespace ImportExportExcel
    {
        public partial class frmImportExecel : Form
        {
    
            private string FilePhat_=string.Empty;
            private DataTable DataTableExel;
           //Hilos
            Thread td;
            public frmImportExecel()
            {
                InitializeComponent();
                DataTableExel = new DataTable();
                this.btnimportexcel.Click += new EventHandler(btnimportexcel_Click);
                this.btnprocesar.Click += new EventHandler(btnprocesar_Click);
                this.btnsalir.Click += new EventHandler(btnsalir_Click);
            }
            /// 
            /// Cierra el formulario
            /// 
            /// 
            /// 
            void btnsalir_Click(object sender, EventArgs e)
            {
                this.Close();
            }
            /// 
            /// Boton para procesar el archivo excel
            /// 
            /// 
            /// 
            void btnprocesar_Click(object sender, EventArgs e)
            {
                if (btnprocesar.Text.Contains("Abortar"))
                {
                    td.Abort();
                    btnprocesar.Enabled = true;
                    btnsalir.Enabled = true;
                    btnimportexcel.Enabled = true;
                    label1.Text = ".....";
                    label4.Text = ".....";
                    progressBar1.Value = 0;
                    dataGridView1.Rows.Clear();// = null;
                    btnprocesar.Text = "Procesar";
                    td = null;
                    label2.Text = "";
                    label3.Text = "0%";
                    Errorproces = false;
                }
                else {
                    ProcesDataExcel();
                }
                
            }
    
            int CantidadRegistro = 0;
            /// 
            /// Boton para abrir el cuadro de dialogo y establecer la
            /// ruta del archivo Excel
            /// 
            /// 
            /// 
            void btnimportexcel_Click(object sender, EventArgs e)
            {
                //Thread file = new Thread(() =>
                //          {
                              OpenFileDialog Abrir = new OpenFileDialog();
                              Abrir.Title = "Arhivo EXCEL";
                              //XLSX-->2010
                              Abrir.Filter = "Excel 2.0 a 2013 |*.xlsx;*.xls";
                              if (Abrir.ShowDialog() == DialogResult.OK){
                                  if (File.Exists(Abrir.FileName))
                                  {
                                    FileInfo existingFile = new FileInfo(Abrir.FileName);
                                    txtphatfile.Text = Abrir.FileName;
                                    FilePhat_ = Abrir.FileName;
                                    btnprocesar.Enabled = true;
                                    progressBar1.Maximum = 100;
                                    Exelversion version = existingFile.Extension==".xls" ? Exelversion.Excel2and2003 : Exelversion.Excel2007and2013;
                                    getDataTableFromExcel(Abrir.FileName, version);//Verficar errores
                                   
                                  }
                              }
            }
    
            int Proceso = 0;
            int Porcentaje=0;
            int notregist = 0;
           bool Errorproces=true;
            /// 
            /// Inserta registros a la base datos
            /// 
            /// 
            private void ProcesDataExcel() {
                Proceso = 0;
                Porcentaje = 0;
                notregist = 0;
                progressBar1.Value = 0;
                label4.Text = "";
                btnsalir.Enabled = false;
                ResourceManager rm = Resources.ResourceManager;
                dataGridView1.Rows.Clear();
                btnprocesar.Enabled = false;
                btnimportexcel.Enabled = false;
                if (MessageBox.Show("Estas seguro de hacer el proceso de importación?", "Información", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK) {
                    td = new Thread(() =>
                    {
                        DataTable EsteProce = DataTableExel;
                        foreach (DataRow Item in EsteProce.Rows)
                        {
                            Proceso++;
                            if (label1.InvokeRequired)
                            {
                                label1.Invoke(new MethodInvoker(delegate
                                {
                                    if (!Errorproces)
                                    {
                                        btnprocesar.Enabled = true;
                                        btnprocesar.Text = "Abortar";
                                        Errorproces = true;
                                    }
    
                                    label1.Text = Proceso.ToString() + " de " + CantidadRegistro.ToString();
    
                                    ConexionDB Registrar = new ConexionDB();
                                    string Query= @"DECLARE @return_status INT;
                                                DECLARE @msg_c nvarchar(70);
                                                EXEC @return_status =dbo.set_transferencia_pro 'REGISTRO',null,'" + Item[0].ToString() + @"', '" + Item[1].ToString() + @"','" + Item[2].ToString() + @"','" + Item[3].ToString() + @"', '" + Item[4].ToString() + @"','" + Item[5].ToString() + @"','" + Item[6].ToString() + @"' 
                                                IF @return_status=1
                                                 BEGIN
                                                   SET @msg_c='{""success"":true,""message"":""Registro guardado correctamente""}'
                                                 END
                                                 ELSE
                                                 BEGIN
                                                   SET @msg_c='{""success"":false,""message"":""Ya existe registro""}'
                                                 END
                                                SELECT @msg_c ";
                                string  JsonReturn = Registrar.ConexionSQL(ConexionDB.Servidores.Sqlserver,Query);
    
                                //string returnmsg = Verificar == "" ? Mensaje : Verificar;
                                JavaScriptSerializer j = new JavaScriptSerializer();
                                ObjetJSON objson = (ObjetJSON)j.Deserialize(JsonReturn.ToString(), typeof(ObjetJSON));
                              
                                 if (objson.success == true)
                                {
                                    Icon Error = new Icon(SystemIcons.Information, 5, 5);
                                    Bitmap resized = new Bitmap(Error.ToBitmap(), new Size(16, 16));
                                    dataGridView1.Rows.Add(resized, "Importado correctamente nº Doc Identidad:" + Item[0].ToString() + " Nombres:" + Item[1].ToString() + " " + Item[2].ToString());
                                }
                                else
                                {
                                    notregist++;
                                    Icon Error = new Icon(SystemIcons.Error, 5, 5);
                                    Bitmap resized = new Bitmap(Error.ToBitmap(), new Size(16, 16));
                                    dataGridView1.Rows.Add(resized, "Ya existe el registro nº cheque:" + Item[0].ToString() + " Pago:" + Item[1].ToString());
                                }
                                    label2.Text = "Doc. Identidad=" + Item[0].ToString() + " Nombre=" + Item[1].ToString() + " " + Item[2].ToString() + "..."; // Recuperamos los registros para mostrar en el proceso
                                    Porcentaje = Convert.ToInt16((((double)Proceso / (double)CantidadRegistro) * 100.00)); //Calcula el porcentaje
                                    label3.Text = Porcentaje.ToString() + "%";// Muestra el porcentaje en valor numérico
                                    progressBar1.Value = Porcentaje;// Establece valor en porcentaje de importación, en el bara progreso
                                    dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.RowCount - 1;//Establece el escroll de la grilla en el último registro
                                    if (CantidadRegistro == Proceso)
                                    {
                                        btnprocesar.Enabled = true;
                                        btnsalir.Enabled = true;
                                        btnimportexcel.Enabled = true;
                                        label1.Text = Proceso.ToString() + " registros procesados.";
                                        label4.Text = (Proceso - notregist).ToString() + " registros importados " + (notregist==0?"": notregist.ToString()+" no importados");
                                    }
                                }));
                            }
                            Thread.Sleep(10);//Dando respiro al servidor.
                        }
                    });
    
                    td.TrySetApartmentState(ApartmentState.STA);
                    td.IsBackground = true;
                    td.Start();
                } 
            }
    
            /// 
            /// Metodo que retorna todo los registros  en un DataTable
            /// 
            /// 
            /// 
            /// 
            public DataTable getDataTableFromExcel(string path,Exelversion Versionexcel)
            {
                DataTable tbl = new DataTable();
                DataSet dataset = new DataSet();
    
                switch (Versionexcel) { 
                    case Exelversion.Excel2and2003:
                         try {
                     var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                       IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream);
                      
                       string Cant = (reader.RowCount-1).ToString();
                       int colCount = (reader.FieldCount-2);
    
                              if (colCount == 7)
                                                   {
                                                       CantidadRegistro = (reader.RowCount - 1);
                                                       label1.Text = "Total a procesar: " + CantidadRegistro.ToString();
                                                   }
    
                    dataset = reader.AsDataSet(new ExcelDataSetConfiguration()
                    {
                        UseColumnDataType = false,
                        ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
                        {
                            UseHeaderRow =true
                            
                        }
                    });
                    tbl = dataset.Tables[0];
                }
                catch (Exception ex) 
                {
                    MessageBox.Show(ex.ToString(), ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
    
    
                        break;
                    case Exelversion.Excel2007and2013:
    
                        try
                        {
                            using (var pck = new OfficeOpenXml.ExcelPackage())
                            {
                                using (var stream = File.OpenRead(path))
                                {
                                    pck.Load(stream);
    
                                }
                                //Vereficacion de columnas
                                                   ExcelWorksheet worksheet = pck.Workbook.Worksheets[1];
                                                   int colCount = worksheet.Dimension.End.Column;
                                                   if (colCount == 7)
                                                   {
                                                       CantidadRegistro = (worksheet.Dimension.End.Row - 1);
                                                       label1.Text = "Total a procesar: " + CantidadRegistro.ToString();
                                                   }
    
                                
    
                                var ws = pck.Workbook.Worksheets.First();
    
                                bool hasHeader = true;
                                foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
                                {
                                    tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
                                }
                                var startRow = hasHeader ? 2 : 1;
                                for (var rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
                                {
                                    var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
                                    var row = tbl.NewRow();
                                    foreach (var cell in wsRow)
                                    {
    
                                        //Validamos  el contenido de las celdas
    
                                        //if ((cell.Start.Column - 1) == 0 || (cell.Start.Column - 1) == 1)
                                        //{
                                        //    if (!cell.Text.IsNumeric()) {
                                        //        throw new InvalidOperationException("Error en la columna: [" + tbl.Columns[(cell.Start.Column - 1)].ColumnName + "], fila: [" + rowNum.ToString() + "] no tiene formato de número");
                                        //        // tbl.Rows.Clear();
                                        //    }
                                        //}
                                        //if ((cell.Start.Column - 1) == 3) {
                                        //    if (!cell.Text.IsDate()) {
                                        //        throw new InvalidOperationException("Error en la columna: [" + tbl.Columns[(cell.Start.Column - 1)].ColumnName + "], fila: [" + rowNum.ToString() + "] no tiene formato de fecha");
                                        //    }
                                        //}
                                        //if ((cell.Start.Column - 1) == 4) {
                                        //    if (cell.Text != "") {
                                        //        if (!cell.Text.IsNumeric())
                                        //        {
                                        //            throw new InvalidOperationException("Error en la columna: [" + tbl.Columns[(cell.Start.Column - 1)].ColumnName + "], fila: [" + rowNum.ToString() + "] no tiene formato de número");
                                        //            // tbl.Rows.Clear();
                                        //        }
                                        //    }
                                        //}
    
                                        row[cell.Start.Column - 1] = cell.Text;
                                    }
                                    tbl.Rows.Add(row);
                                }
                                DataTableExel = tbl;
                                return tbl;
                            }
                        }
                        catch (Exception es)
                        {
                            MessageBox.Show(es.Message, "Información", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            btnprocesar.Enabled = false;
                        }
                        break;
                }
                DataTableExel = tbl;
                return tbl;
            }
    
            private void frmImportcheques_FormClosing(object sender, FormClosingEventArgs e)
            {
    
               //Cancelamos el cierre de ventana mientras el proceso de importación se ejecuta.
                if (!Nullable.Equals(td, null)){
                    if (td.ThreadState == ThreadState.Stopped){
                        td.Abort();
                    } else {
                        e.Cancel = true;  
                    }
                }
            }
        }
        public static class Extensions
        {
    
            /// 
            ///Expresión regular para validar caracteres númericos
            /// 
            /// 
            /// 
           public static bool IsNumeric(this string str)
            {
                Regex _isNumericRegex =
        new Regex("^(" +
                    /*Hex*/ @"0x[0-9a-f]+" + "|" +
                    /*Bin*/ @"0b[01]+" + "|" +
                    /*Oct*/ @"0[0-7]*" + "|" +
                    /*Dec*/ @"((?!0)|[-+]|(?=0+\.))(\d*\,)?\d+(\d*\.)?\d+(e\d+)?" +
                    ")$");
                return _isNumericRegex.IsMatch(str);
            }
    
            //Expresión regular para validar fechas
           public static bool IsDate(this string str) { 
             Regex Isdate=new Regex(@"^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$");
                return Isdate.IsMatch(str);
           }
            /// 
            /// Expresión regular para validar fechas y la hora incluyendo los segundos
            /// 
            /// 
            /// 
            public static bool IdateLong(this string srt) {
               Regex Isdatehour = new Regex(@"^(0[0-9]|[0-9]||1\d|2[0-8]|29(?=-\d\d-(?!1[01345789]00|2[1235679]00)\d\d(?:[02468][048]|[13579][26]))|30(?!-02)|31(?=-0[13578]|-1[02]))+\/([1-9]|1[0-2]|0[1-9]|1[0-2])\/([12]\d{3}) ([01]\d|2[0-3]):([0-5]\d):([0-5]\d)$");
               return Isdatehour.IsMatch(srt);
           }
            /// 
            /// Returns true if string is numeric and not empty or null or whitespace.
            /// Determines if string is numeric by parsing as Double
            /// 
            /// 
            /// Optional style - defaults to NumberStyles.Number (leading and trailing whitespace, leading and trailing sign, decimal point and thousands separator) 
            /// Optional CultureInfo - defaults to InvariantCulture
            /// 
            //public static bool IsNumeric(this string str)
            //{
            //    double num;
               
            //    return Double.TryParse(str, out num) && !String.IsNullOrWhiteSpace(str);
            //}
        }
    
    
    public class ConexionDB{
    
        public enum Servidores { 
        Mysql,
        Postgresql,
        Sqlserver
        }
        DataTable Tabla = new System.Data.DataTable();
        public DataTable TablaRegistro { get { return this.Tabla;} }
        public string ConexionSQL( Servidores Myservidor ,string Query) {
            string ReturnText = "";
          
          
            switch (Myservidor) { 
                case Servidores.Mysql:
                   string   ConexionIndex = "Server=localhost; database=test; UID=root; password=; SslMode=none";
                        //MySqlConnection Conexion = new MySqlConnection(ConexionIndex);
                        //Conexion.Open();
                        //MySqlDataAdapter Comand = new MySqlDataAdapter(Query, Conexion);
                        //Comand.Fill(Tabla);
                        //DataRow Fila = Tabla.Rows[0];
                        //ReturnText = Fila[0].ToString();
                        //Conexion.Close();
                        break;
                case Servidores.Sqlserver:
                    string Conexionindex = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=prueba;Integrated Security=True";
                    SqlConnection Conexionsqlserver = new SqlConnection(Conexionindex);
                    Conexionsqlserver.Open();
                    SqlDataAdapter adaptar = new SqlDataAdapter(Query, Conexionsqlserver);
                    adaptar.Fill(Tabla);
                        if (Tabla.Rows.Count>0)
                        {
                            DataRow Filadata = Tabla.Rows[0];
                            ReturnText = Filadata[0].ToString();
    
                        }
                        else { 
                         ReturnText ="";
                        }
                
                    Conexionsqlserver.Close();
                    break;
    
            }
            return ReturnText;
        }
    }
       
        public class ObjetJSON {
            public bool success { get; set; }
            public string message { get; set; }
        }
        public enum Exelversion { 
          Excel2and2003,
          Excel2007and2013
        }
    }
    
    

    Formulario de registro y edición

    En el tercer formulario contendrá campos de texto para registrar y editar datos.

    El código de formulario de inserción y edición se muestra a continuación.

    
    
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Globalization;
    using System.Linq;
    using System.Web.Script.Serialization;
    using System.Windows.Forms;
    
    namespace ImportExportExcel
    {
        public partial class frmregistrar : Form
        {
            public frmregistrar()
            {
                InitializeComponent();
                this.btnaceptar.Click += btnaceptar_Click;
                this.Load += Frmregistrar_Load;
                btncancelar.Click += Btncancelar_Click;
            }
    
            private void Btncancelar_Click(object sender, EventArgs e)
            {
                this.Close();
            }
    
            private void Frmregistrar_Load(object sender, EventArgs e)
            {
                if (Id != null) {
                    txtIdentida.Text = this.DocIdentidad.ToString();
                    txtnombre.Text= this.Nombre ;
                    txtapellidopat.Text= this.ApellidoPaterno;
                    txtapmaterno.Text=this.ApellidoMaterno;
                    txtimporte.Text=this.Importe.ToString();
                    txtceuntaban.Text=this.CuentaBancaria;
                    txtinstfin.Text=this.InstitucionBancaria ;
                    this.btnaceptar.Text = "Editar";
                }
            }
    
            void btnaceptar_Click(object sender, EventArgs e)
            {
                //frmregistrar nuevo = new frmregistrar();
                //nuevo.DocIdentidad =
                if (txtIdentida.Text != "" && txtIdentida.Text.IsNumeric())
                {
                    errorProvider1.SetError(txtIdentida, null);
                    if (txtnombre.Text != "")
                    {
                        errorProvider1.SetError(txtnombre, null);
                        if (txtapellidopat.Text != "")
                        {
                            errorProvider1.SetError(txtapellidopat, null);
                            if (txtapmaterno.Text != "")
                            {
                                errorProvider1.SetError(txtapmaterno, null);
                                if (txtimporte.Text != "" && txtimporte.Text.IsNumeric())
                                {
                                    errorProvider1.SetError(txtimporte, null);
                                    if (txtceuntaban.Text != "" && txtceuntaban.Text.IsNumeric())
                                    {
                                        errorProvider1.SetError(txtceuntaban, null);
                                        if (txtinstfin.Text != "")
                                        {
                                            errorProvider1.SetError(txtinstfin, null);
    
                                            if (btnaceptar.Text.Contains("Editar"))
                                            {
                                                frmregistrar nuevo = new frmregistrar();
                                                nuevo.DocIdentidad = Convert.ToDecimal(txtIdentida.Text);
                                                nuevo.Nombre = txtnombre.Text;
                                                nuevo.ApellidoPaterno = txtapellidopat.Text;
                                                nuevo.ApellidoMaterno = txtapmaterno.Text;
                                                nuevo.Importe = Convert.ToDecimal(txtimporte.Text);
                                                nuevo.CuentaBancaria = txtceuntaban.Text;
                                                nuevo.InstitucionBancaria = txtinstfin.Text;
    
                                                ConexionDB Registrar = new ConexionDB();
                                                string Query = @"DECLARE @return_status INT;
                                                DECLARE @msg_c nvarchar(70);
                                                EXEC @return_status =dbo.set_transferencia_pro 'EDITAR','"+this.Id.ToString()+"','" + nuevo.DocIdentidad.ToString() + @"', '" + nuevo.Nombre + @"','" + nuevo.ApellidoPaterno + @"','" + nuevo.ApellidoMaterno + @"', '" + String.Format(CultureInfo.InvariantCulture, "{0:0.0}", nuevo.Importe)  + @"','" + nuevo.CuentaBancaria + @"','" + nuevo.InstitucionBancaria + @"' 
                                                IF @return_status=1
                                                 BEGIN
                                                   SET @msg_c='{""success"":true,""message"":""Registro modificado correctamente""}'
                                                 END
                                                SELECT @msg_c ";
                                                string JsonReturn = Registrar.ConexionSQL(ConexionDB.Servidores.Sqlserver, Query);
    
                                                //string returnmsg = Verificar == "" ? Mensaje : Verificar;
                                                JavaScriptSerializer j = new JavaScriptSerializer();
                                                ObjetJSON objson = (ObjetJSON)j.Deserialize(JsonReturn.ToString(), typeof(ObjetJSON));
                                                if (objson.success)
                                                {
                                                    MessageBox.Show("Registro modificado correctamente", "Mensaje");
                                                    txtapellidopat.Clear();
                                                    txtapmaterno.Clear();
                                                    txtIdentida.Clear();
                                                    txtnombre.Clear();
                                                    txtinstfin.Clear();
                                                    txtimporte.Clear();
                                                    txtceuntaban.Clear();
                                                }
                                            }
                                            else {
                                                frmregistrar nuevo = new frmregistrar();
                                                nuevo.DocIdentidad = Convert.ToDecimal(txtIdentida.Text);
                                                nuevo.Nombre = txtnombre.Text;
                                                nuevo.ApellidoPaterno = txtapellidopat.Text;
                                                nuevo.ApellidoMaterno = txtapmaterno.Text;
                                                nuevo.Importe = Convert.ToDecimal(txtimporte.Text);
                                                nuevo.CuentaBancaria = txtceuntaban.Text;
                                                nuevo.InstitucionBancaria = txtinstfin.Text;
    
                                                ConexionDB Registrar = new ConexionDB();
                                                string Query = @"DECLARE @return_status INT;
                                                DECLARE @msg_c nvarchar(70);
                                                EXEC @return_status =dbo.set_transferencia_pro 'REGISTRO',null,'" + nuevo.DocIdentidad.ToString() + @"', '" + nuevo.Nombre + @"','" + nuevo.ApellidoPaterno + @"','" + nuevo.ApellidoMaterno + @"', '" + nuevo.Importe.ToString() + @"','" + nuevo.CuentaBancaria + @"','" + nuevo.InstitucionBancaria + @"' 
                                                IF @return_status=1
                                                 BEGIN
                                                   SET @msg_c='{""success"":true,""message"":""Registro guardado correctamente""}'
                                                 END
                                                 ELSE
                                                 BEGIN
                                                   SET @msg_c='{""success"":false,""message"":""Ya existe registro""}'
                                                 END
                                                SELECT @msg_c ";
                                                string JsonReturn = Registrar.ConexionSQL(ConexionDB.Servidores.Sqlserver, Query);
    
                                                //string returnmsg = Verificar == "" ? Mensaje : Verificar;
                                                JavaScriptSerializer j = new JavaScriptSerializer();
                                                ObjetJSON objson = (ObjetJSON)j.Deserialize(JsonReturn.ToString(), typeof(ObjetJSON));
                                                if (objson.success)
                                                {
                                                    MessageBox.Show("Registro guardado correctamente", "Mensaje");
                                                    txtapellidopat.Clear();
                                                    txtapmaterno.Clear();
                                                    txtIdentida.Clear();
                                                    txtnombre.Clear();
                                                    txtinstfin.Clear();
                                                    txtimporte.Clear();
                                                    txtceuntaban.Clear();
                                                }
                                            }
    
                                          
    
                                        }
                                        else {
                                            errorProvider1.SetError(txtinstfin, "Por favor escriba el nombre de la institución financiera.");
                                        }
    
                                    }
                                    else {
                                        errorProvider1.SetError(txtceuntaban, "Por favor escriba cuenta bancaria númerico.");
                                    }
                                }
                                else {
                                    errorProvider1.SetError(txtimporte, "Por favor escriba importe númerico.");
                                }
                            }
                            else {
                                errorProvider1.SetError(txtapmaterno, "Por favor escriba apellido materno.");
                            }
    
                        }
                        else {
                            errorProvider1.SetError(txtapellidopat, "Por favor escriba oapellido paterno.");
                        }
                    }
                    else {
                        errorProvider1.SetError(txtnombre, "Por favor escriba Nombre.");
                    }
    
                }
                else {
                    errorProvider1.SetError(txtIdentida,"Por favor escriba nº documento de identidad númerico.");
                }
                
            }
    
            public int? Id { get; set; }
            public decimal? DocIdentidad { get; set; }
            public string Nombre { get; set; }
            public string ApellidoPaterno { get; set; }
            public string ApellidoMaterno { get; set; }
            public decimal? Importe { get; set; }
            public string CuentaBancaria { get; set; }
            public string InstitucionBancaria { get; set; }
            /// 
            /// Para convertir los registro de db a una lista de objetos
            /// 
            /// 
            /// 
            public List Datos(DataTable Tabla) { 
            
                var Lista=Tabla.AsEnumerable()
                  .Select(Item => new frmregistrar
                  {
                      Id = Item.Field("opt_idtransfe"),
                      DocIdentidad = Item.Field("opt_docidentidad"),
                      Nombre = Item.Field("opt_nombres"),
                      ApellidoPaterno = Item.Field("opt_appaterno"),
                      ApellidoMaterno = Item.Field("opt_materno"),
                      Importe = Item.Field("opt_importe"),
                      CuentaBancaria = Item.Field("opt_cuentaban"),
                      InstitucionBancaria = Item.Field("opt_insbanaria"),
                  }).ToList();
                return Lista;
            }
        }
    
    }
    
    
    Sobre el autor
    Rodrigo Chambi Q.

    Desarrollador de aplicaciones web y de escritorio, amante de la tecnología y autodidacta, me gusta conocer otras tecnologías, escribir artículos para compartir en la web y para estar al tanto en los nuevos paradigmas, respeto las políticas de software privativo y libre, ya que estas políticas son las normas que permite el desarrollo tecnológico social de la humanidad. filvovmax@gmail.com -- info@gitmedio.com

    Deja una respuesta

    Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

    Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.