Hace un par de días, un compañero me llamo a preguntarme si conocía como pasar o exportar los datos de una grilla (DatagridView) en .Net C# a un archivo Excel. Fue aquí, donde recordé que había hecho algo parecido hace algún tiempo. Este código por su necesidad en la mayoría de las aplicaciones (Exportar datos) puede llegar a ser muy útil y quiero que lo tengan con ustedes.
Empecemos explicando un poco la funcionalidad del ejemplo.
Los datos que voy a mostrar en la grilla vienen de un procedimiento almacenado, estos registros los almaceno en una variable publica de tipo DataSet, la cual se encarga de poblar o llenar la Grilla y finalmente exporta los datos ha Excel. Les muestro el código para ser un poco mas claro.
Declaramos de Variable Dataset
DataSet dsDatos = new DataSet();
Se llena la variable con la consulta que viene de base de datos y se muestran los datos en la Grilla.
SqlCommand cmd = new SqlCommand(sSql, connDB); SqlDataAdapter DaRecDatos = new SqlDataAdapter(cmd); DaRecDatos.Fill(dsDatos); dataGridView1.DataSource = dsDatos;
Para exportar los datos llamo al Dataset (dsDatos) que previamente llenamos y se lo pasamos aun método llamado, para este ejemplo ExportarAexcel que se encargara de exportar los datos en la ruta que seleccionamos en el FileDialog, así:
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Excel Files (*.xls)|*.xls";// All Files (*.*)|*.*";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
FileName = saveFileDialog.FileName;
if (FileName.Trim() != "")
{
if (ExportarAexcel(dsDatos, FileName, ref sError))
{
return true;
}
}
}
Anexo método que exporta los datos:
public static bool ExportarAexcel(DataSet source, string fileName,ref string sErr)
{
try
{
System.IO.StreamWriter excelDoc;
excelDoc = new System.IO.StreamWriter(fileName);
const string startExcelXML = "\r\n\r\n \r\n " +
"\r\n " +
"\r\n " +
"\r\n \r\n " +
"\r\n \r\n " +
" \r\n ";
const string endExcelXML = " ";
int rowCount = 0;
int sheetCount = 1;
excelDoc.Write(startExcelXML);
excelDoc.Write("");
excelDoc.Write("");
excelDoc.Write("");
for (int x = 0; x < source.Tables[0].Columns.Count; x++)
{
excelDoc.Write("| ");
excelDoc.Write(source.Tables[0].Columns[x].ColumnName);
excelDoc.Write(" | ");
}
excelDoc.Write("
");
foreach (DataRow x in source.Tables[0].Rows)
{
rowCount++;
//if the number of rows is > 64000 create a new page to continue output
if (rowCount == 64000)
{
rowCount = 0;
sheetCount++;
excelDoc.Write("
");
excelDoc.Write(" ");
excelDoc.Write("");
excelDoc.Write("");
}
excelDoc.Write(""); //ID=" + rowCount + "
for (int y = 0; y < source.Tables[0].Columns.Count; y++)
{
System.Type rowType;
rowType = x[y].GetType();
switch (rowType.ToString())
{
case "System.String":
string XMLstring = x[y].ToString();
XMLstring = XMLstring.Trim();
XMLstring = XMLstring.Replace("&", "&");
XMLstring = XMLstring.Replace(">", ">");
XMLstring = XMLstring.Replace("<", "<");
excelDoc.Write("| " +
"");
excelDoc.Write(XMLstring);
excelDoc.Write(" | ");
break;
case "System.DateTime":
//Excel has a specific Date Format of YYYY-MM-DD followed by
//the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
//The Following Code puts the date stored in XMLDate
//to the format above
DateTime XMLDate = (DateTime)x[y];
string XMLDatetoString = ""; //Excel Converted Date
XMLDatetoString = XMLDate.Year.ToString() +
"-" +
(XMLDate.Month < 10 ? "0" +
XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
"-" +
(XMLDate.Day < 10 ? "0" +
XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
"T" +
(XMLDate.Hour < 10 ? "0" +
XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
":" +
(XMLDate.Minute < 10 ? "0" +
XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
":" +
(XMLDate.Second < 10 ? "0" +
XMLDate.Second.ToString() : XMLDate.Second.ToString()) +
".000";
excelDoc.Write("" +
"");
excelDoc.Write(XMLDatetoString);
excelDoc.Write(" | ");
break;
case "System.Boolean":
excelDoc.Write("" +
"");
excelDoc.Write(x[y].ToString());
excelDoc.Write(" | ");
break;
case "System.Int16":
case "System.Int32":
case "System.Int64":
case "System.Byte":
excelDoc.Write("" +
"");
excelDoc.Write(x[y].ToString());
excelDoc.Write(" | ");
break;
case "System.Decimal":
case "System.Double":
excelDoc.Write("" +
"");
excelDoc.Write(x[y].ToString());
excelDoc.Write(" | ");
break;
case "System.DBNull":
excelDoc.Write("" +
"");
excelDoc.Write("");
excelDoc.Write(" | ");
break;
default:
throw (new Exception(rowType.ToString() + " not handled."));
}
}
excelDoc.Write("
");
}
excelDoc.Write("
");
excelDoc.Write(" ");
excelDoc.Write(endExcelXML);
excelDoc.Close();
}
catch (Exception ex)
{
sErr = ex.Message;
return false;
}
return true;
}
Si desean conocer como Exportar un DaTable a formato CSV no dejen de visitarlo es una funcionalidad que los puede sacar de apuros en cualquier proyecto.
"" Si tienes dudas o quieras ampliar este artículo, lo puedes hacer dejando tus comentarios. Además, si lo consideras interesante puedes compartirlo con amigos y seguidores a través de los botones sociales que aparecen en esta página.""



