Skip to content

Instantly share code, notes, and snippets.

@jofese
Created August 10, 2017 16:11
Show Gist options
  • Save jofese/bdfd66db6707ea72a7ed04b74804b0ba to your computer and use it in GitHub Desktop.
Save jofese/bdfd66db6707ea72a7ed04b74804b0ba to your computer and use it in GitHub Desktop.
exportar un datagridview a excel
public static void exportarDataGridView(ToolStripProgressBar Barra, DataGridView lista , string titulo)
{
try
{
Barra.Value = 0;
Barra.Visible = true;
Barra.Maximum = lista.Rows.Count;
Microsoft.Office.Interop.Excel.Application libro = new Microsoft.Office.Interop.Excel.Application();
libro.Workbooks.Add(true);
//Microsoft.Office.Interop.Excel.Application libro = new Microsoft.Office.Interop.Excel.Application();
//libro.Workbooks.Add(true);
libro.Cells[1, 1] = titulo;
int cIndex = 0, rIndex = 3;
//Recorres las columnas
foreach (DataGridViewColumn sCol in lista.Columns)
{
cIndex += 1;
libro.Cells[3, cIndex] = sCol.HeaderText;
}
//Recorres las Filas
foreach (DataGridViewRow sitem in lista.Rows)
{
Barra.Value += 1;
rIndex += 1;
cIndex = 0;
foreach (DataGridViewColumn sCol in lista.Columns)
{
cIndex += 1;
libro.Cells[rIndex + 1, cIndex] = sitem.Cells[cIndex - 1].Value;
}
}
//Muestras el archivo Excel.
libro.Visible = true;
Barra.Visible = false;
}
catch
{
MessageBox.Show("No se pudo realizar la operación", "CLINICA SANCHEZ FERRER", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment