C sharp - Ayuda con carga masiva de productos

 
Vista:
sin imagen de perfil

Ayuda con carga masiva de productos

Publicado por Fede (5 intervenciones) el 16/07/2023 20:00:24
Buen Domingo para todos, se trata de una carga masiva de productos que importamos de Excel a una BD sqllite.

Funciona a la perfecciòn, sólo que requiero modificarle una cosa.

Cuando el Codigo del producto ya existe lo que hace el programa es decirle que no lo vuelva a agregar, de tal modo que no existan productos repetidos, caso contrario lo agrega.

Yo quiero modificar lo siguiente: que si el codigo del producto ya existe, entonces modifique los otros campos de ese producto.

Va a continuar no habiendo duplicados, cada vez que cargue un producto repetido va a modificarlo.

Espero haberme explicado bien


Aquí dejo el codigo


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            if (permitir_carga)
            {
                if (txtarchivo.Text.Trim() != "")
                {
                    List<Producto> oListaProducto = new List<Producto>();
                    IWorkbook MiExcel = null;
                    FileStream fs = new FileStream(txtarchivo.Text, FileMode.Open, FileAccess.Read);
                    MiExcel = new XSSFWorkbook(fs);
                    ISheet hoja = MiExcel.GetSheetAt(0);
 
                    for (int row = 1; row <= hoja.LastRowNum; row++)
                    {
                        if (hoja.GetRow(row) != null)
                        {
                            string msjExiste = string.Empty;
                            string msjGuardar = string.Empty;
                            IRow fila = hoja.GetRow(row);
                            Producto oProducto = new Producto();
                            try
                            {
                                oProducto = new Producto()
                                {
                                    Codigo = fila.GetCell(0, MissingCellPolicy.RETURN_NULL_AND_BLANK) != null ? fila.GetCell(0).StringCellValue.ToString() : "",
                                    Descripcion = fila.GetCell(1, MissingCellPolicy.RETURN_NULL_AND_BLANK) != null ? fila.GetCell(1).StringCellValue.ToString() : "",
                                    Categoria = fila.GetCell(2, MissingCellPolicy.RETURN_NULL_AND_BLANK) != null ? fila.GetCell(2).StringCellValue.ToString() : "",
                                    Medida = fila.GetCell(3, MissingCellPolicy.RETURN_NULL_AND_BLANK) != null ? fila.GetCell(3).StringCellValue.ToString() : "",
                                };
                            }
                            catch
                            {
                                oProducto = null;
                            }
 
                            if (oProducto != null)
                            {
                                int existe = ProductoLogica.Instancia.Existe(oProducto.Codigo, 0, out msjExiste);
                                if (existe > 0)
                                {
                                    table.Rows.Add(row.ToString(), oProducto.Codigo, msjExiste, "x");
                                }
                                else
                                {
                                    int idgenerado = ProductoLogica.Instancia.Guardar(oProducto, out msjGuardar);
                                    if (idgenerado < 1)
                                    {
                                        table.Rows.Add(row.ToString(), oProducto.Codigo, msjGuardar, "x");
                                    }
                                    else
                                    {
                                        table.Rows.Add(row.ToString(), oProducto.Codigo, "Registrado Correctamente", "");
                                    }
                                }
 
                            }
 
                            backgroundWorker1.ReportProgress(row);
                        }
                    }
                }
 
 
            }
            else
            {
                MessageBox.Show("Cargue el archivo correcto", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
 
 
 
 
 
 
 
 
 
 
 
public int Existe(string codigo, int defaultid, out string mensaje)
        {
            mensaje = string.Empty;
            int respuesta = 0;
            using (SQLiteConnection conexion = new SQLiteConnection(Conexion.cadena))
            {
                try
                {
                    conexion.Open();
                    StringBuilder query = new StringBuilder();
                    query.AppendLine("select count(*)[resultado] from PRODUCTO where upper(Codigo) = upper(@pcodigo) and IdProducto != @defaultid");
 
                    SQLiteCommand cmd = new SQLiteCommand(query.ToString(), conexion);
                    cmd.Parameters.Add(new SQLiteParameter("@pcodigo", codigo));
                    cmd.Parameters.Add(new SQLiteParameter("@defaultid", defaultid));
                    cmd.CommandType = System.Data.CommandType.Text;
 
                    respuesta = Convert.ToInt32(cmd.ExecuteScalar().ToString());
                    if (respuesta > 0)
                        mensaje = "El codigo de producto ya existe";
 
                }
                catch (Exception ex)
                {
                    respuesta = 0;
                    mensaje = ex.Message;
                }
 
            }
            return respuesta;
        }
 
        public int Guardar(Producto objeto, out string mensaje)
        {
            mensaje = string.Empty;
            int respuesta = 0;
 
            using (SQLiteConnection conexion = new SQLiteConnection(Conexion.cadena))
            {
                try
                {
 
                    conexion.Open();
                    StringBuilder query = new StringBuilder();
 
                    query.AppendLine("insert into PRODUCTO(Codigo,Descripcion,Categoria,Medida) values (@pcodigo,@pdescripcion,@pcategoria,@pmedida);");
                    query.AppendLine("select last_insert_rowid();");
 
                    SQLiteCommand cmd = new SQLiteCommand(query.ToString(), conexion);
                    cmd.Parameters.Add(new SQLiteParameter("@pcodigo", objeto.Codigo));
                    cmd.Parameters.Add(new SQLiteParameter("@pdescripcion", objeto.Descripcion));
                    cmd.Parameters.Add(new SQLiteParameter("@pcategoria", objeto.Categoria));
                    cmd.Parameters.Add(new SQLiteParameter("@pmedida", objeto.Medida));
                    cmd.CommandType = System.Data.CommandType.Text;
 
                    respuesta = Convert.ToInt32(cmd.ExecuteScalar().ToString());
                    if (respuesta < 1)
                        mensaje = "No se pudo registrar el producto";
                }
                catch (Exception ex)
                {
                    respuesta = 0;
                    mensaje = ex.Message;
                }
            }
 
            return respuesta;
        }
 
        public int Editar(Producto objeto, out string mensaje)
        {
            mensaje = string.Empty;
            int respuesta = 0;
 
            using (SQLiteConnection conexion = new SQLiteConnection(Conexion.cadena))
            {
                try
                {
 
                    conexion.Open();
                    StringBuilder query = new StringBuilder();
 
                    query.AppendLine("update PRODUCTO set Codigo = @pcodigo,Descripcion = @pdescripcion,Categoria =@pcategoria ,Medida = @pmedida where IdProducto = @pidproducto");
 
                    SQLiteCommand cmd = new SQLiteCommand(query.ToString(), conexion);
                    cmd.Parameters.Add(new SQLiteParameter("@pidproducto", objeto.IdProducto));
                    cmd.Parameters.Add(new SQLiteParameter("@pcodigo", objeto.Codigo));
                    cmd.Parameters.Add(new SQLiteParameter("@pdescripcion", objeto.Descripcion));
                    cmd.Parameters.Add(new SQLiteParameter("@pcategoria", objeto.Categoria));
                    cmd.Parameters.Add(new SQLiteParameter("@pmedida", objeto.Medida));
                    cmd.CommandType = System.Data.CommandType.Text;
 
                    respuesta = cmd.ExecuteNonQuery();
                    if (respuesta < 1)
                        mensaje = "No se pudo editar el producto";
                }
                catch (Exception ex)
                {
                    respuesta = 0;
                    mensaje = ex.Message;
                }
            }
 
            return respuesta;
        }
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder