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

Ayuda con Excel

Estas en el tema de Ayuda con Excel en el foro de ASPX (.net) en Foros del Web. Que tal tengo un problema,espero alguien me pueda ayudar actualmente tengo un grid el cual lleno dependiendo una consulta y despues lo exporto a una ...
  #1 (permalink)  
Antiguo 17/12/2007, 13:29
 
Fecha de Ingreso: diciembre-2003
Mensajes: 595
Antigüedad: 20 años, 4 meses
Puntos: 1
Ayuda con Excel

Que tal tengo un problema,espero alguien me pueda ayudar actualmente tengo un grid el cual lleno dependiendo una consulta y despues lo exporto a una hoja de ecel hasta alli ningun problema pero el problema es que a veces o ya esta sucediendo muy seguido no me cabe la cantidad de datos en la hoja ecedo su limite de ecel alguien me podria decir que podria hacer para no tener limite d datos o alguna otra propuesta
  #2 (permalink)  
Antiguo 19/12/2007, 09:58
Avatar de txarly  
Fecha de Ingreso: marzo-2003
Ubicación: Eibar (Gipuzkoa)
Mensajes: 455
Antigüedad: 21 años, 1 mes
Puntos: 2
Re: Ayuda con Excel

Yo utilizo una función que exporta el contenido de un Dataset a Excel, cuando supera el nº máximo de filas lo que hace es crear otra pagina y continuar añadiendo los resultados. Por si te sirve te dejo el código:

Cita:
/// <summary>
/// Función para exportar un DataSet a Excel
/// </summary>
/// <param name="source"></param>
/// <param name="fileName"></param>
public void ExportToExcel(DataSet source, string fileName)
{

System.IO.StreamWriter excelDoc;

/*
<xml version>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
<Styles>
<Style ss:ID="Default" ss:Name="Normal">
<Alignment ss:Vertical="Bottom"/>
<Borders/>
<Font/>
<Interior/>
<NumberFormat/>
<Protection/>
</Style>
<Style ss:ID="BoldColumn">
<Font x:Family="Swiss" ss:Bold="1"/>
</Style>
<Style ss:ID="StringLiteral">
<NumberFormat ss:Format="@"/>
</Style>
<Style ss:ID="Decimal">
<NumberFormat ss:Format="0.0000"/>
</Style>
<Style ss:ID="Integer">
<NumberFormat ss:Format="0"/>
</Style>
<Style ss:ID="DateLiteral">
<NumberFormat ss:Format="dd/mm/yyyy;@"/>
</Style>
</Styles>
<Worksheet ss:Name="Sheet1">
</Worksheet>
</Workbook>
*/

excelDoc = new System.IO.StreamWriter(fileName);
const string startExcelXML = "<xml version>\r\n<Workbook " +
"xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
" xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
"xmlns:x=\"urn:schemas-microsoft-com:office:" +
"excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" +
"office:spreadsheet\">\r\n <Styles>\r\n " +
"<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
"<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
"\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
"\r\n <Protection/>\r\n </Style>\r\n " +
"<Style ss:ID=\"BoldColumn\">\r\n <Font " +
"x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
"<Style ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
" ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
"ss:ID=\"Decimal\">\r\n <NumberFormat " +
"ss:Format=\"0.0000\"/>\r\n </Style>\r\n " +
"<Style ss:ID=\"Integer\">\r\n <NumberFormat " +
"ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
"ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
"ss:Format=\"dd/mm/yyyy;@\"/>\r\n </Style>\r\n " +
"</Styles>\r\n ";
const string endExcelXML = "</Workbook>";

int rowCount = 0;
int sheetCount = 1;

excelDoc.Write(startExcelXML);
excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
excelDoc.Write("<Table>");
excelDoc.Write("<Row>");
for (int x = 0; x < source.Tables[0].Columns.Count; x++)
{
excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
excelDoc.Write(source.Tables[0].Columns[x].ColumnName);
excelDoc.Write("</Data></Cell>");
}
excelDoc.Write("</Row>");
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("</Table>");
excelDoc.Write(" </Worksheet>");
excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
excelDoc.Write("<Table>");
}
excelDoc.Write("<Row>"); //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("<Cell ss:StyleID=\"StringLiteral\">" +
"<Data ss:Type=\"String\">");
excelDoc.Write(XMLstring);
excelDoc.Write("</Data></Cell>");
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("<Cell ss:StyleID=\"DateLiteral\">" +
"<Data ss:Type=\"DateTime\">");
excelDoc.Write(XMLDatetoString);
excelDoc.Write("</Data></Cell>");
break;

case "System.Boolean":
excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
"<Data ss:Type=\"String\">");
excelDoc.Write(x[y].ToString());
excelDoc.Write("</Data></Cell>");
break;

case "System.Int16":
case "System.Int32":
case "System.Int64":
case "System.Byte":
excelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
"<Data ss:Type=\"Number\">");
excelDoc.Write(x[y].ToString());
excelDoc.Write("</Data></Cell>");
break;

case "System.Decimal":
case "System.Double":
excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
"<Data ss:Type=\"Number\">");
excelDoc.Write(x[y].ToString());
excelDoc.Write("</Data></Cell>");
break;

case "System.DBNull":
excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
"<Data ss:Type=\"String\">");
excelDoc.Write("");
excelDoc.Write("</Data></Cell>");
break;

default:
throw (new Exception(rowType.ToString() + " not handled."));

}
}
excelDoc.Write("</Row>");
}
excelDoc.Write("</Table>");
excelDoc.Write(" </Worksheet>");
excelDoc.Write(endExcelXML);
excelDoc.Close();
}
Un saludo
__________________
¿Por qué Uri Geller doblaba cucharas?
  #3 (permalink)  
Antiguo 19/12/2007, 10:53
 
Fecha de Ingreso: diciembre-2003
Mensajes: 595
Antigüedad: 20 años, 4 meses
Puntos: 1
Re: Ayuda con Excel

Ok muchas gracias deja lo pruebo y te comento como me fue
  #4 (permalink)  
Antiguo 19/12/2007, 11:01
 
Fecha de Ingreso: diciembre-2003
Mensajes: 595
Antigüedad: 20 años, 4 meses
Puntos: 1
Re: Ayuda con Excel

Cita:
Iniciado por txarly Ver Mensaje
Yo utilizo una función que exporta el contenido de un Dataset a Excel, cuando supera el nº máximo de filas lo que hace es crear otra pagina y continuar añadiendo los resultados. Por si te sirve te dejo el código:



Un saludo
Oye una pregunta yo hago mi consulta asi

SqlConnection conn = new SqlConnection("Server=172.16.3.21;Database=Courier max;Uid=prueba;Pwd=prueba SqlCommand cmd = new SqlCommand();

cmd.CommandType = CommandType.Text;
cmd.CommandText = "select top * from cmusr.CM_CONTROL ";
cmd.Connection = conn;

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);

da.Fill(ds);
DataGrid1.DataSource = ds;
DataGrid1.DataBind();

//y aqui invoco tu funcion asi o dime si la estoy invocando mal

ExportToExcel(ds,"prueba");





de ante mano te agradesco por tu ayuda
  #5 (permalink)  
Antiguo 20/12/2007, 10:38
Avatar de txarly  
Fecha de Ingreso: marzo-2003
Ubicación: Eibar (Gipuzkoa)
Mensajes: 455
Antigüedad: 21 años, 1 mes
Puntos: 2
Re: Ayuda con Excel

En el segundo parámetro indicale el path físico ó la ruta donde vás a guardar el archivo Excel:

String strPath = @"C:\Temp\prueba.xls";
ExportToExcel(ds, strPath);

Lo demás está OK
__________________
¿Por qué Uri Geller doblaba cucharas?
  #6 (permalink)  
Antiguo 21/12/2007, 07:39
 
Fecha de Ingreso: diciembre-2003
Mensajes: 595
Antigüedad: 20 años, 4 meses
Puntos: 1
Re: Ayuda con Excel

oye me envia el siguiente error

Access to the path "C:\prueb.xls" is denied.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.UnauthorizedAccessException: Access to the path "C:\prueb.xls" is denied.

ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6) that is used if the application is not impersonating. If the application is impersonating via <identity impersonate="true"/>, the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.

To grant ASP.NET write access to a file, right-click the file in Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.

Source Error:


Line 94: */
Line 95:
Line 96: excelDoc = new System.IO.StreamWriter(fileName);
Line 97: const string startExcelXML = "<xml version>\r\n<Workbook " +
Line 98: "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
  #7 (permalink)  
Antiguo 28/12/2007, 07:53
 
Fecha de Ingreso: diciembre-2003
Mensajes: 595
Antigüedad: 20 años, 4 meses
Puntos: 1
Re: Ayuda con Excel

Cita:
Iniciado por txarly Ver Mensaje
En el segundo parámetro indicale el path físico ó la ruta donde vás a guardar el archivo Excel:

String strPath = @"C:\Temp\prueba.xls";
ExportToExcel(ds, strPath);

Lo demás está OK

OK ya corregi el error que me enviaba era porque el archivo no tenia permisos de escritura pero ahora cuando trato de eportar mas de 60,000 registros me envia este mensaje

  #8 (permalink)  
Antiguo 28/12/2007, 15:00
 
Fecha de Ingreso: mayo-2004
Ubicación: Guadalajara, Jalisco, México
Mensajes: 724
Antigüedad: 19 años, 11 meses
Puntos: 6
Re: Ayuda con Excel

Yo he usado otra manera,.. utilizando los componentes de office,

http://www.elguille.info/colabora/pu...celReports.htm
y
http://www.eggheadcafe.com/articles/20021012.asp

Salu2
  #9 (permalink)  
Antiguo 28/12/2007, 15:48
 
Fecha de Ingreso: diciembre-2003
Mensajes: 595
Antigüedad: 20 años, 4 meses
Puntos: 1
Re: Ayuda con Excel

Cita:
Iniciado por Stream Ver Mensaje
Yo he usado otra manera,.. utilizando los componentes de office,

http://www.elguille.info/colabora/pu...celReports.htm
y
http://www.eggheadcafe.com/articles/20021012.asp

Salu2
me serviria el segundo ya que mi aplicaicon esta en C# pero me marca error
  #10 (permalink)  
Antiguo 04/01/2008, 07:55
 
Fecha de Ingreso: diciembre-2003
Mensajes: 595
Antigüedad: 20 años, 4 meses
Puntos: 1
Re: Ayuda con Excel

Alguien sabe porque me marca este error al abrir el archivo que me exporto la funcion




Me lo envia al tratar de habrir mi hoja de calculo con 65,000 registros exportados
  #11 (permalink)  
Antiguo 09/01/2008, 05:05
 
Fecha de Ingreso: noviembre-2007
Mensajes: 15
Antigüedad: 16 años, 5 meses
Puntos: 0
Re: Ayuda con Excel

Yo tuve un problema parecido, pero lo solucioné así:

Código PHP:
        private void cmdInformeUser_Click(object senderSystem.EventArgs e)
        {
            
// Utilizamos una librería externa llamada "ExportToExcel" para poder realizar la operación
            // de escribir en el fichero de Excel los datos de la base de datos
            //
            // Lo hemos utilizado de CodeProject de esta URL:
            // http://www.codeproject.com/KB/office/Excel_Export.aspx
            
ExportToExcel.ExcelExport objExport = new ExportToExcel.ExcelExport();

            
// Definimos el directorio temporal
            
objExport.TempFolder = @"\temp\";
            // Definimos el directorio de la plantilla
            objExport.TemplateFolder = @"
template";
            // Definimos el estilo del XLS
            objExport.XSLStyleSheetFolder = @"
XSLStyleSheet";
            // Limpiamos de ficheros temporales, puesto que cada vez que se crea un fichero de Excel,
            // se van acumulando. De este modo se impide que ocurra.
            objExport.CleanUpTemporaryFiles();

            // Definimos la consulta
            string sSel = "
select idUsernamesurnamescompanyniftelephonemobilefaxemailcountrycityaddressnumberfloorcplogin from users order by idUser desc";
            // Definimos el fichero
            string fichero="";

            // Definimos las variables para realizar la consulta a la base de datos
            SqlDataAdapter da;
            DataTable dt = new DataTable();
            System.Data.SqlClient.SqlCommandBuilder commbuilder;
            System.Data.DataSet dset = new System.Data.DataSet();
    
            try
            {
                // Abrimos la conexión y rellenamos los datos al dataset
                da = new SqlDataAdapter(sSel, conexion);
                commbuilder = new System.Data.SqlClient.SqlCommandBuilder(da);
                da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
                da.Fill(dset);
                // Metemos datos al DataGrid
                this.dg.DataSource = dset;
                this.dg.DataBind();
            }
            // Si hay error, se muestra
            catch(Exception ex)
            {
                Response.Write("
Error" + ex.Message);
            }
            // Transformamos los datos de la tabla de la Grid en un formato que pueda ser leído
            // por Excel
            fichero=objExport.TransformDataTableToExcel(dset.Tables[0],true);

            // Lo exportamos a un fichero (nos aparecerá una ventanita diciendo si desea guardar
            // el fichero
            objExport.SendExcelToClient(fichero);
        } 
Sin problemas y funciona correctamente. Además me pasaba cosas raras (con el código que se ha puesto de los primeros) con Vista y con XP funcionaba bien. Pero fue hacer eso y ya no hay fallo...

Es mejor ponerlo en una carpeta aparte, para que no dé fallos. En mi caso lo hice con temp.

Saludos.
  #12 (permalink)  
Antiguo 09/01/2008, 09:14
 
Fecha de Ingreso: diciembre-2003
Mensajes: 595
Antigüedad: 20 años, 4 meses
Puntos: 1
Re: Ayuda con Excel

lo voy a checar gracias
  #13 (permalink)  
Antiguo 09/01/2008, 14:29
 
Fecha de Ingreso: diciembre-2003
Mensajes: 595
Antigüedad: 20 años, 4 meses
Puntos: 1
Re: Ayuda con Excel

Cita:
Iniciado por Kurace Ver Mensaje
Yo tuve un problema parecido, pero lo solucioné así:

Código PHP:
        private void cmdInformeUser_Click(object senderSystem.EventArgs e)
        {
            
// Utilizamos una librería externa llamada "ExportToExcel" para poder realizar la operación
            // de escribir en el fichero de Excel los datos de la base de datos
            //
            // Lo hemos utilizado de CodeProject de esta URL:
            // http://www.codeproject.com/KB/office/Excel_Export.aspx
            
ExportToExcel.ExcelExport objExport = new ExportToExcel.ExcelExport();

            
// Definimos el directorio temporal
            
objExport.TempFolder = @"\temp\";
            // Definimos el directorio de la plantilla
            objExport.TemplateFolder = @"
template";
            // Definimos el estilo del XLS
            objExport.XSLStyleSheetFolder = @"
XSLStyleSheet";
            // Limpiamos de ficheros temporales, puesto que cada vez que se crea un fichero de Excel,
            // se van acumulando. De este modo se impide que ocurra.
            objExport.CleanUpTemporaryFiles();

            // Definimos la consulta
            string sSel = "
select idUsernamesurnamescompanyniftelephonemobilefaxemailcountrycityaddressnumberfloorcplogin from users order by idUser desc";
            // Definimos el fichero
            string fichero="";

            // Definimos las variables para realizar la consulta a la base de datos
            SqlDataAdapter da;
            DataTable dt = new DataTable();
            System.Data.SqlClient.SqlCommandBuilder commbuilder;
            System.Data.DataSet dset = new System.Data.DataSet();
    
            try
            {
                // Abrimos la conexión y rellenamos los datos al dataset
                da = new SqlDataAdapter(sSel, conexion);
                commbuilder = new System.Data.SqlClient.SqlCommandBuilder(da);
                da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
                da.Fill(dset);
                // Metemos datos al DataGrid
                this.dg.DataSource = dset;
                this.dg.DataBind();
            }
            // Si hay error, se muestra
            catch(Exception ex)
            {
                Response.Write("
Error" + ex.Message);
            }
            // Transformamos los datos de la tabla de la Grid en un formato que pueda ser leído
            // por Excel
            fichero=objExport.TransformDataTableToExcel(dset.Tables[0],true);

            // Lo exportamos a un fichero (nos aparecerá una ventanita diciendo si desea guardar
            // el fichero
            objExport.SendExcelToClient(fichero);
        } 
Sin problemas y funciona correctamente. Además me pasaba cosas raras (con el código que se ha puesto de los primeros) con Vista y con XP funcionaba bien. Pero fue hacer eso y ya no hay fallo...

Es mejor ponerlo en una carpeta aparte, para que no dé fallos. En mi caso lo hice con temp.

Saludos.
Ya lo cheque Gracias y funciona bien solo que hay un problema cuando hace la consulta digamos unos 100,000 registros en la hoja de excel solo caben 65,000 y no me aparecen los demas, pero lo adapte con el codigo que gentilmente me envio txarly, pero cuando export a tal informacion me sige enviando la pantalla de error

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 07:42.