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

Exportar DatagridView. Funciona, pero...

Estas en el tema de Exportar DatagridView. Funciona, pero... en el foro de .NET en Foros del Web. Hola a todos, tengo la siguiente funcion para exportar un datagridview, en VB 2005, a Excel. La forma de operar, es copiar en memoria el ...
  #1 (permalink)  
Antiguo 16/08/2009, 21:18
 
Fecha de Ingreso: junio-2009
Mensajes: 14
Antigüedad: 14 años, 10 meses
Puntos: 0
Exportar DatagridView. Funciona, pero...

Hola a todos, tengo la siguiente funcion para exportar un datagridview, en VB 2005, a Excel.
La forma de operar, es copiar en memoria el contendio de todo el datagrid y pegarlo en una nueva hoja de excel.

El código es el siguiente.

Código:
Private Sub ButtonExp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


        System.Threading.Thread.CurrentThread.CurrentCulture = _
      System.Globalization.CultureInfo.CreateSpecificCulture("en-US")


        DataGridView1.SelectAll()
        DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText
        Clipboard.SetDataObject(DataGridView1.GetClipboardContent())
        appExcel = New Excel.Application
        appExcel.SheetsInNewWorkbook = 1
        wbExcel = appExcel.Workbooks.Add
        appExcel.Visible = True
        wbExcel.Worksheets(1).range("A1").Select()
        wbExcel.Worksheets(1).Paste()
    End Sub
Funciona bien, pero quisiera agregarle un par de cosas. primero seleccionar solo algunas celdas para copiar y pegar (un rango).

Y segundo, y lo mas importante, es que quisiera que la hoja se grabara automaticamente, lo he hecho agregando esta linea

appExcel.SaveWorkspace()

con esa linea se abre el cuadro de dialogo para grabar, pero si el usuario no guarda el doc y pone "cancelar", el programa se cae.

Necesito solucionar ese par de cosas, he buscado bastante antes de consultar aca, espero que me puedan ayudar.

Les agradezco, de antemano, su valiosa ayuda.

Muchas Gracias!!
  #2 (permalink)  
Antiguo 17/08/2009, 07:49
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. Funciona, pero...

Yo uso esta funcion...

Exporta a excel el contenido de un grid automaticamente al pulsar un boton y te almacena en un directorio predetermindado...

Cita:
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
Cita:
ExportaExcel(DataGrid1, "exportedData", ".xls", _
My.Computer.FileSystem.SpecialDirectories.Desktop)
Cita:

Private Sub ExportaExcel(ByVal grdView As DataGridView, ByVal fileName As String, _
ByVal fileExtension As String, ByVal filePath As String)
fileExtension = ".xls"
fileName = "DatosExcel" & 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

Saludos
  #3 (permalink)  
Antiguo 18/08/2009, 15:10
 
Fecha de Ingreso: junio-2009
Mensajes: 14
Antigüedad: 14 años, 10 meses
Puntos: 0
Respuesta: Exportar DatagridView. Funciona, pero...

gracias por tu sugerencia... lo probe, pero me marca error en

Dim fs As New IO.StreamWriter(myFile, False)

espero que me puedas ayudar... muchas gracias
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 11:34.