Foros del Web » Programando para Internet » ASPX (.net) »

ASP.NET AJAX Exportar un DataTable a Excel en VB.NET

Estas en el tema de ASP.NET AJAX Exportar un DataTable a Excel en VB.NET en el foro de ASPX (.net) en Foros del Web. Hola amigos, necesito una solución, sin usar componente de terceros, que me permita generar un archivo de excel a partir de un DataTable. He buscado ...
  #1 (permalink)  
Antiguo 13/04/2010, 15:45
 
Fecha de Ingreso: julio-2005
Mensajes: 18
Antigüedad: 18 años, 9 meses
Puntos: 0
ASP.NET AJAX Exportar un DataTable a Excel en VB.NET

Hola amigos, necesito una solución, sin usar componente de terceros, que me permita generar un archivo de excel a partir de un DataTable.

He buscado por todos lados en la web y todas las soluciones lo hacen con Response.Write, pero este no funciona con Ajax.

Gracias
  #2 (permalink)  
Antiguo 14/04/2010, 07:50
Avatar de jaullo  
Fecha de Ingreso: abril-2009
Mensajes: 994
Antigüedad: 15 años
Puntos: 30
Respuesta: ASP.NET AJAX Exportar un DataTable a Excel en VB.NET

Prueba esto

http://www.codeproject.com/KB/aspnet...52#xx2567252xx

http://www.webpronews.com/expertarti...table-to-excel
  #3 (permalink)  
Antiguo 19/04/2010, 04:54
 
Fecha de Ingreso: octubre-2006
Ubicación: Madrid
Mensajes: 23
Antigüedad: 17 años, 6 meses
Puntos: 0
Respuesta: ASP.NET AJAX Exportar un DataTable a Excel en VB.NET

Hace poco tuve el mismo problema.

Te pongo el código que hice, está en c# pero te puede dar una idea de lo que tienes que hacer.

Elimina la parte de los logs de los catch, puesto que he utilizado una clase de los que he programado yo, lo único que hace es salvar los mensajes a un fichero.

using System;
using System.Data;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;

public class ToExcel
{
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;

string filePath, fileName;
Log log;

public ToExcel(String strFileName, Log log)
{
try
{
fileName = strFileName;
this.log = log;

oXL = new Excel.Application();
filePath = oXL.GetSaveAsFilename(fileName, "Archivos de Excel (*.xls), *.xls", 1, "Guardar prueba", Missing.Value).ToString();
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value) ); // crear el Workbook
oSheet = (Excel._Worksheet)oWB.ActiveSheet; // crear la Hoja
}
catch (Exception ex)
{
if (log.getLogActivo())
{
log.abrirFicherosLog();
log.WriteError("ERROR en el constructor ToExcel()::" + ex.Message);
log.CerrarFicherosLog();
}
throw ex;
}
}

public void guardarHistorico(DataSet dataSet,string strNombreHistorico)
{

try
{
oSheet.Name = strNombreHistorico; //Nombre de la hoja

int intColumnas = dataSet.Tables[0].Columns.Count;
string strColumna = convertirChar(intColumnas);

//1.- Damos el formato a la cabecera
oSheet.get_Range("A1", strColumna + "1").Font.Name = "Verdana";
oSheet.get_Range("A1", strColumna + "1").Font.Size = 10;
oSheet.get_Range("A1", strColumna + "1").Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawin g.Color.White);
oSheet.get_Range("A1", strColumna + "1").Font.Bold = true;
oSheet.get_Range("A1", strColumna + "1").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
oSheet.get_Range("A1", strColumna + "1").Interior.Pattern = Excel.XlPattern.xlPatternSolid;
oSheet.get_Range("A1", strColumna + "1").Interior.ColorIndex = 23;

oSheet.get_Range("A1", "B" + dataSet.Tables[0].Rows.Count + 1).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;

//2.- Creamos la cabecera de la tabla
int intCol = 1;
foreach (DataColumn dc in dataSet.Tables[0].Columns)
{
oSheet.Cells[1, intCol] = dc.ColumnName;
strColumna = convertirChar(intCol) + "1";
switch (dc.ColumnName){
case "Fecha" :
oSheet.get_Range(strColumna, strColumna).ColumnWidth = dc.ColumnName.Length + 15; //Ancho de la columna
break;
case "Descripcion" :
oSheet.get_Range(strColumna, strColumna).ColumnWidth = 60; //Ancho de la columna
break;
case "Resultado" :
oSheet.get_Range(strColumna, strColumna).ColumnWidth = 15;
break;
}
intCol++;
}

//3.- Introducimos los datos del dataSet en la hoja Excel
int intFila = 1;
foreach (DataRow dr in dataSet.Tables[0].Rows)
{
intCol = 1;
foreach (DataColumn dc in dataSet.Tables[0].Columns)
{
if (dr[intCol - 1] is string || dr[intCol - 1] is String)
{
oSheet.Cells[intFila + 1, intCol] = (String)dr[intCol - 1];
}
else if (dr[intCol - 1] is int)
{
oSheet.Cells[intFila + 1, intCol] = (int)dr[intCol - 1];
}
else if (dr[intCol - 1] is DateTime)
{
oSheet.Cells[intFila + 1, intCol] = ((DateTime)dr[intCol - 1]).ToString("dd/MM/yyyy hh:mm");
}

intCol++;
}

//4.- Cambiamos el color de fondo de las filas de forma alternativa
if (intFila % 2 == 0)
{
oSheet.get_Range("A" + (intFila + 1), convertirChar(intCol - 1) + (intFila + 1)).Interior.ColorIndex = 2;
}
else
{
oSheet.get_Range("A" + (intFila + 1), convertirChar(intCol - 1) + (intFila + 1)).Interior.ColorIndex = 19;
}

intFila++;
}
/*
//Si se desea visualizar el fichero
oXL.Visible = true;
oXL.UserControl = true;
*/

//5.- Guardamos el fichero y eliminamos los procesos de Excel creados
guardarFichero();
}
catch (Exception ex)
{
if (log.getLogActivo())
{
log.abrirFicherosLog();
log.WriteError("ERROR en ToExcel.guardarHistorico()::" + ex.Message);
log.CerrarFicherosLog();
}
}
}

public void guardarFichero()
{
try
{
//1.- Guardamos el fichero
oXL.ActiveWorkbook.Close(true, filePath, Type.Missing);
oXL.Quit();
oXL = null;

//2.- Liberamos los recursos
System.Diagnostics.Process[] myProcesses;
myProcesses = System.Diagnostics.Process.GetProcessesByName("EXC EL");
foreach (System.Diagnostics.Process instance in myProcesses)
{
instance.CloseMainWindow();
instance.Kill();
instance.Close();
}
}
catch (Exception ex)
{
if (log.getLogActivo())
{
log.abrirFicherosLog();
log.WriteError("ERROR en ToExcel.guardarFichero()::" + ex.Message);
log.CerrarFicherosLog();
}
}
}

public string convertirChar(int n)
{
string tabla64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (n > 0)
{
return tabla64.Substring(n - 1, 1);
}
else
{
return "A";
}
}
}

Suerte!!

Etiquetas: ajax, datatable, excel, aspx
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 17:03.