Foros del Web » Programación para mayores de 30 ;) » .NET »

Exportar DatagridView a xls de Excel

Estas en el tema de Exportar DatagridView a xls de Excel en el foro de .NET en Foros del Web. Hola a todos. Estoy teniendo un problema con un datagridview generado dinámicamente. Quiero exportarlo a excel para despues cargarlo con CristalResports. Pero a la hora ...
  #1 (permalink)  
Antiguo 12/01/2010, 13:57
 
Fecha de Ingreso: mayo-2008
Mensajes: 117
Antigüedad: 15 años, 10 meses
Puntos: 0
Exportar DatagridView a xls de Excel

Hola a todos. Estoy teniendo un problema con un datagridview generado dinámicamente.

Quiero exportarlo a excel para despues cargarlo con CristalResports.

Pero a la hora de crear el libro de excel me da error.

He hechop la referencia a crosoft.Office.Interop.Excel

Y lo exporto de la siguiente manera:

Código ASP:
Ver original
  1. If n_Filas = 0 Then
  2.             MsgBox("No hay datos para exportar a excel. Se ha indicado 0 en el parámetro Filas ") : Exit Sub
  3.         Else
  4.  
  5.             ' -- Crear nueva instancia de Excel  
  6.             excel = New Microsoft.Office.Interop.Excel.Application
  7.  
  8.            'Aquí me de el error!!!
  9.             wBook = excel.Workbooks.Add()
  10.             wSheet = wBook.ActiveSheet()
  11.  
  12.  
  13.             Dim iCol As Integer = 0
  14.             For i = 0 To DG.Columns.Count - 1
  15.                 If DG.Columns(i).Visible Then
  16.  
  17.                     iCol = iCol + 1
  18.                     wSheet.Cells(1, iCol) = DG.Columns(i).HeaderText
  19.                 End If
  20.             Next
  21.  
  22.             For i = 0 To DG.Rows.Count - 1
  23.                 iCol = iCol + 1
  24.                 For j = 0 To DG.Columns.Count - 1
  25.                     wSheet.Cells(j + 2, iCol) = DG.Rows(i).Cells(j).Value
  26.                 Next
  27.             Next
  28.  
  29.             wSheet.Columns.AutoFit()
  30.             Dim strFileName As String = "D:\ss.xls"
  31.             Dim blnFileOpen As Boolean = False
  32.             Try
  33.                 Dim fileTemp As System.IO.FileStream = System.IO.File.OpenWrite(strFileName)
  34.                 fileTemp.Close()
  35.             Catch ex As Exception
  36.                 blnFileOpen = False
  37.             End Try
  38.  
  39.             If System.IO.File.Exists(strFileName) Then
  40.                 System.IO.File.Delete(strFileName)
  41.             End If
  42.  
  43.             wBook.SaveAs(strFileName)
  44.             excel.Workbooks.Open(strFileName)
  45.             excel.Visible = True
  46.         End If

'Aquí me de el error!!!

wBook = excel.Workbooks.Add()


Gracias!
  #2 (permalink)  
Antiguo 13/01/2010, 09:01
 
Fecha de Ingreso: mayo-2008
Mensajes: 117
Antigüedad: 15 años, 10 meses
Puntos: 0
Respuesta: Exportar DatagridView a xls de Excel

Nadie sabe como hacerlo?
  #3 (permalink)  
Antiguo 14/01/2010, 08:49
Avatar de atak  
Fecha de Ingreso: julio-2005
Ubicación: Huancayo
Mensajes: 490
Antigüedad: 18 años, 9 meses
Puntos: 5
De acuerdo Exportar DatagridView a xls de Excel

Hola Krato

tengo el ejemplo en CSharp
si puede ayudarte .. en hora buena.


Link


Saludos
__________________
. .: El mejor Inicio :. .
  #4 (permalink)  
Antiguo 15/01/2010, 10:54
Avatar de Darkavender  
Fecha de Ingreso: septiembre-2008
Ubicación: SLV
Mensajes: 125
Antigüedad: 15 años, 7 meses
Puntos: 4
Respuesta: Exportar DatagridView a xls de Excel

Esta es la funcion que yop uso...

ojala te sirva


Cita:
Private Sub BtnExcel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnExcel.Click


ExportaExcel(DtGrdClientes, "exportedData", ".xls", _
My.Computer.FileSystem.SpecialDirectories.Desktop)
End Sub

Private Declare Function ShellEx Lib "shell32.dll" Alias "ShellExecuteA" ( _
ByVal hWnd As Integer, ByVal lpOperation As String, _
ByVal lpFile As String, ByVal lpParameters As String, _
ByVal lpDirectory As String, ByVal nShowCmd As Integer) As Integer


Private Sub ExportaExcel(ByVal grdView As DataGridView, ByVal fileName As String, _
ByVal fileExtension As String, ByVal filePath As String)
fileExtension = ".xls"
fileName = "ClientesGCA-" & Hour(Now()) & Minute(Now()) & Second(Now())

' Choose the path, name, and extension for the Excel file
Dim myFile As String = "DocExcel\" & fileName & fileExtension

' Open the file and write the headers
Dim fs As New IO.StreamWriter(myFile, False)
fs.WriteLine("<?xml version=""1.0""?>")
fs.WriteLine("<?mso-application progid=""Excel.Sheet""?>")
fs.WriteLine("<ss:Workbook xmlns:ss=""urn:schemas-microsoft-com:office:spreadsheet"">")

' Create the styles for the worksheet
fs.WriteLine(" <ss:Styles>")
' Style for the column headers
fs.WriteLine(" <ss:Style ss:ID=""1"">")
fs.WriteLine(" <ss:Font ss:Bold=""1""/>")
fs.WriteLine(" <ss:Alignment ss:Horizontal=""Center"" ss:Vertical=""Center"" " & _
"ss:WrapText=""1""/>")
fs.WriteLine(" <ss:Interior ss:Color=""#C0C0C0"" ss:Pattern=""Solid""/>")
fs.WriteLine(" </ss:Style>")
' Style for the column information
fs.WriteLine(" <ss:Style ss:ID=""2"">")
fs.WriteLine(" <ss:Alignment ss:Vertical=""Center"" ss:WrapText=""1""/>")
fs.WriteLine(" </ss:Style>")
fs.WriteLine(" </ss:Styles>")

' Write the worksheet contents
fs.WriteLine("<ss:Worksheet ss:Name=""Sheet1"">")
fs.WriteLine(" <ss:Table>")
For i As Integer = 0 To grdView.Columns.Count - 1
fs.WriteLine(String.Format(" <ss:Column ss:Width=""{0}""/>", _
grdView.Columns.Item(i).Width))
Next
fs.WriteLine(" <ss:Row>")
For i As Integer = 0 To grdView.Columns.Count - 1
fs.WriteLine(String.Format(" <ss:Cell ss:StyleID=""1"">" & _
"<ss:Data ss:Type=""String"">{0}</ss:Data></ss:Cell>", _
grdView.Columns.Item(i).HeaderText))
Next
fs.WriteLine(" </ss:Row>")

' Check for an empty row at the end due to Adding allowed on the DataGridView
Dim subtractBy As Integer, cellText As String
If grdView.AllowUserToAddRows = True Then subtractBy = 2 Else subtractBy = 1
' Write contents for each cell
For i As Integer = 0 To grdView.RowCount - subtractBy
fs.WriteLine(String.Format(" <ss:Row ss:Height=""{0}"">", _
grdView.Rows(i).Height))
For intCol As Integer = 0 To grdView.Columns.Count - 1
cellText = grdView.Item(intCol, i).Value
' Check for null cell and change it to empty to avoid error
If cellText = vbNullString Then cellText = ""
fs.WriteLine(String.Format(" <ss:Cell ss:StyleID=""2"">" & _
"<ss:Data ss:Type=""String"">{0}</ss:Data></ss:Cell>", _
cellText.ToString))
Next
fs.WriteLine(" </ss:Row>")
Next

' Close up the document
fs.WriteLine(" </ss:Table>")
fs.WriteLine("</ss:Worksheet>")
fs.WriteLine("</ss:Workbook>")
fs.Close()

' Open the file in Microsoft Excel
' 10 = SW_SHOWDEFAULT
ShellEx(Me.Handle, "Open", myFile, "", "", 10)
End Sub
  #5 (permalink)  
Antiguo 15/01/2010, 21:15
 
Fecha de Ingreso: diciembre-2009
Mensajes: 137
Antigüedad: 14 años, 4 meses
Puntos: 4
Respuesta: Exportar DatagridView a xls de Excel

hola

yo tengo un codigo en vb .net si te sirve me avisas para q lo pruebes
  #6 (permalink)  
Antiguo 16/01/2010, 06:56
Avatar de gnzsoloyo
Moderador criollo
 
Fecha de Ingreso: noviembre-2007
Ubicación: Actualmente en Buenos Aires (el enemigo ancestral)
Mensajes: 23.324
Antigüedad: 16 años, 4 meses
Puntos: 2658
Respuesta: Exportar DatagridView a xls de Excel

Cita:
Hola a todos. Estoy teniendo un problema con un datagridview generado dinámicamente.

Quiero exportarlo a excel para despues cargarlo con CristalResports.

Pero a la hora de crear el libro de excel me da error.

He hechop la referencia a Microsoft.Office.Interop.Excel

Y lo exporto de la siguiente manera:
El problema es a qué versión de Office vas a exportar.
Si usas Office 2000 ó 2003, no deberías tener problemas con tu código. Pero si usas Office 2007, los formatos y los objetos son incompatibles...
La solución de Darkavender sería la mejor, porque lo que hace es generar un XML que si puede ser entendido por las tres versiones de Office.

Por otro lado, otro problema es qué versión de VS estés usando...
__________________
¿A quién le enseñan sus aciertos?, si yo aprendo de mis errores constantemente...
"El problema es la interfase silla-teclado." (Gillermo Luque)

Etiquetas: datagridview, excel, xls
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 14:11.