Generate an Excel file from c #

0

I have an information in a datagrid that I load directly from the SQL database, I need to generate an excel file with the previously loaded information including the headers.

How could I do it?

    
asked by Ramón Zoquier 31.03.2017 в 21:54
source

2 answers

0

This is an example of how to use it.

Let's see if it helps you.

protected void ibExcele_Click(object sender, ImageClickEventArgs e)
        {                        
            // Crear un objeto SqlConnection, y luego pasar la ConnectionString al constructor.            
            SqlConnection Conection = new SqlConnection(CadenaString);

            // Utilizar una variable para almacenar la instrucción SQL.
            string SelectString = "SELECT id_pregunta, descripcion, opcion, valor_respuesta, COUNT(id_estudiante) AS Numero_Votos FROM respuestas_encuentas, preguntas WHERE respuestas_encuentas.id_pregunta = preguntas.id GROUP BY id_pregunta, opcion, descripcion, valor_respuesta";                        

            SqlDataAdapter Adaptador = new SqlDataAdapter(SelectString, Conection);

            DataSet DS = new DataSet();

            // Abrir la conexión.
            Conection.Open();
            Adaptador.Fill(DS);
            Conection.Close();

            // Creamos un objeto Excel.
            Excel.Application Mi_Excel = default(Excel.Application);
            // Creamos un objeto WorkBook. Para crear el documento Excel.           
            Excel.Workbook LibroExcel = default(Excel.Workbook);
            // Creamos un objeto WorkSheet. Para crear la hoja del documento.
            Excel.Worksheet HojaExcel = default(Excel.Worksheet);            

            // Iniciamos una instancia a Excel, y Hacemos visibles para ver como se va creando el reporte, 
            // podemos hacerlo visible al final si se desea.
            Mi_Excel = new Excel.Application();
            Mi_Excel.Visible = true;

            /* Ahora creamos un nuevo documento y seleccionamos la primera hoja del 
             * documento en la cual crearemos nuestro informe. 
             */
            // Creamos una instancia del Workbooks de excel.            
            LibroExcel = Mi_Excel.Workbooks.Add();
            // Creamos una instancia de la primera hoja de trabajo de excel            
            HojaExcel = LibroExcel.Worksheets[1];
            HojaExcel.Visible = Excel.XlSheetVisibility.xlSheetVisible;

            // Hacemos esta hoja la visible en pantalla 
            // (como seleccionamos la primera esto no es necesario
            // si seleccionamos una diferente a la primera si lo
            // necesitariamos).
            HojaExcel.Activate();

            // Crear el encabezado de nuestro informe.
            // La primera línea une las celdas y las convierte un en una sola.            
            HojaExcel.Range["A1:E1"].Merge();
            // La segunda línea Asigna el nombre del encabezado.
            HojaExcel.Range["A1:E1"].Value = "----------------------------------------------";
            // La tercera línea asigna negrita al titulo.
            HojaExcel.Range["A1:E1"].Font.Bold = true;
            // La cuarta línea signa un Size a titulo de 15.
            HojaExcel.Range["A1:E1"].Font.Size = 15;            

            // Crear el subencabezado de nuestro informe
            HojaExcel.Range["A2:E2"].Merge();
            HojaExcel.Range["A2:E2"].Value = "ENCUESTA DE SATISFACCIÓN AL CLIENTE EXTERNO";
            HojaExcel.Range["A2:E2"].Font.Italic = true;
            HojaExcel.Range["A2:E2"].Font.Size = 13;            

            Excel.Range objCelda = HojaExcel.Range["A3", Type.Missing];
            objCelda.Value = "ID";

            objCelda = HojaExcel.Range["B3", Type.Missing];
            objCelda.Value = "Preguntas";

            objCelda = HojaExcel.Range["C3", Type.Missing];
            objCelda.Value = "Opciones";

            objCelda = HojaExcel.Range["D3", Type.Missing];
            objCelda.Value = "Valor de la Respuesta";

            objCelda = HojaExcel.Range["E3", Type.Missing];
            objCelda.Value = "Numero Votos";

            objCelda.EntireColumn.NumberFormat = "###,###,###.00";

            int i = 4;
            foreach (DataRow Row in DS.Tables[0].Rows)
            {
                // Asignar los valores de los registros a las celdas
                HojaExcel.Cells[i, "A"] = Row.ItemArray[0];
                // ID
                HojaExcel.Cells[i, "B"] = Row.ItemArray[1];
                // Pregunta
                HojaExcel.Cells[i, "C"] = Row.ItemArray[2];
                // Opciones
                HojaExcel.Cells[i, "D"] = Row.ItemArray[3];
                // Valor de la Respuesta
                HojaExcel.Cells[i, "E"] = Row.ItemArray[4];
                // Numero Votos

                // Avanzamos una fila
                i++;
            }

            // Seleccionar todo el bloque desde A1 hasta D #de filas.
            Excel.Range Rango = HojaExcel.Range["A3:E" + (i - 1).ToString()];

            // Selecionado todo el rango especificado
            Rango.Select();

            // Ajustamos el ancho de las columnas al ancho máximo del
            // contenido de sus celdas
            Rango.Columns.AutoFit();

            // Asignar filtro por columna
            Rango.AutoFilter(1);            

            // Crear un total general
            //LibroExcel.PrintPreview();
        }
    
answered by 31.03.2017 / 22:05
source
0

I use this method, but to make it work you must add, to your project, reference to Excel COM (in my case it is Microsoft Excel 15.0 Object Library, because I have Office 2013)

void ExportarDataGridViewExcel(DataGridView grd)
    {
        using (SaveFileDialog fichero = new SaveFileDialog { Filter = @"Excel (*.xls)|*.xls" })
        {
            if (fichero.ShowDialog() == DialogResult.OK)
            {
                Microsoft.Office.Interop.Excel.Application aplicacion = new Microsoft.Office.Interop.Excel.Application();
                Workbook librosTrabajo = aplicacion.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
                Worksheet hojaTrabajo = (Worksheet)librosTrabajo.Worksheets.get_Item(1);
                int iCol = 0;
                foreach (DataGridViewColumn column in dataGridView1.Columns)
                    if (column.Visible)
                        hojaTrabajo.Cells[1, ++iCol] = column.HeaderText;
                for (int i = 0; i < grd.Rows.Count - 1; i++)
                {
                    for (int j = 0; j < grd.Columns.Count; j++)
                    {
                        hojaTrabajo.Cells[i + 2, j + 1] = grd.Rows[i].Cells[j].Value.ToString();
                    }
                }
                librosTrabajo.SaveAs(fichero.FileName, XlFileFormat.xlWorkbookNormal,
                                      System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, false,
                                      XlSaveAsAccessMode.xlShared, false, false,
                                      System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
                aplicacion.Quit();
            }
        }
    }

I hope it helps you.

Edit: as a parameter you must pass the datagridview that you want to export.

    
answered by 01.04.2017 в 00:55