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

Exportar datagrid a word, access..

Estas en el tema de Exportar datagrid a word, access.. en el foro de .NET en Foros del Web. Hola foreros. Tengo un datagrid con registros de una base de datos. Necesito hacer exportaciones y buscando por google me he topado una clase muy ...
  #1 (permalink)  
Antiguo 02/03/2008, 12:17
 
Fecha de Ingreso: noviembre-2006
Mensajes: 437
Antigüedad: 17 años, 5 meses
Puntos: 3
Exportar datagrid a word, access..

Hola foreros. Tengo un datagrid con registros de una base de datos. Necesito hacer exportaciones y buscando por google me he topado una clase muy interesante que me hace la funcion en excel.
Pongo la clase:

Cita:
Imports System.Data
Imports System.IO
Imports Microsoft.Office.Interop

Public Class Funciones

Public Sub DataTableToExcel(ByVal pDataTable As DataTable)

Dim vFileName As String = Path.GetTempFileName()

FileOpen(1, vFileName, OpenMode.Output)

Dim sb As String
Dim dc As DataColumn
For Each dc In pDataTable.Columns
sb &= dc.Caption & Microsoft.VisualBasic.ControlChars.Tab
Next
PrintLine(1, sb)

Dim i As Integer = 0
Dim dr As DataRow
For Each dr In pDataTable.Rows
i = 0 : sb = ""
For Each dc In pDataTable.Columns
If Not IsDBNull(dr(i)) Then
sb &= CStr(dr(i)) & Microsoft.VisualBasic.ControlChars.Tab
Else
sb &= Microsoft.VisualBasic.ControlChars.Tab
End If
i += 1
Next

PrintLine(1, sb)
Next
FileClose(1)
TextToExcel(vFileName)

End Sub

Public Sub TextToExcel(ByVal pFileName As String)

Dim vFormato As Excel.XlRangeAutoFormat

Dim vCultura As System.Globalization.CultureInfo = System.Threading.Thread.CurrentThread.CurrentCultu re
System.Threading.Thread.CurrentThread.CurrentCultu re = System.Globalization.CultureInfo.CreateSpecificCul ture("en-US")

Dim Exc As Excel.Application = New Excel.Application
Exc.Workbooks.OpenText(pFileName, , , , Excel.XlTextQualifier.xlTextQualifierNone, , True)

Dim Wb As Excel.Workbook = Exc.ActiveWorkbook
Dim Ws As Excel.Worksheet = Wb.ActiveSheet

'Se le indica el formato al que queremos exportarlo
Dim valor As Integer = 1
If valor > -1 Then
Select Case valor
Case 0 : vFormato = Excel.XlRangeAutoFormat.xlRangeAutoFormatNone
Case 1 : vFormato = Excel.XlRangeAutoFormat.xlRangeAutoFormatSimple
Case 2 : vFormato = Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic1
Case 3 : vFormato = Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2
Case 4 : vFormato = Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic3
Case 5 : vFormato = Excel.XlRangeAutoFormat.xlRangeAutoFormatAccountin g1
Case 6 : vFormato = Excel.XlRangeAutoFormat.xlRangeAutoFormatAccountin g2
Case 7 : vFormato = Excel.XlRangeAutoFormat.xlRangeAutoFormatAccountin g3
Case 8 : vFormato = Excel.XlRangeAutoFormat.xlRangeAutoFormatAccountin g4
Case 9 : vFormato = Excel.XlRangeAutoFormat.xlRangeAutoFormatColor1
Case 10 : vFormato = Excel.XlRangeAutoFormat.xlRangeAutoFormatColor2
Case 11 : vFormato = Excel.XlRangeAutoFormat.xlRangeAutoFormatColor3
Case 12 : vFormato = Excel.XlRangeAutoFormat.xlRangeAutoFormatList1
Case 13 : vFormato = Excel.XlRangeAutoFormat.xlRangeAutoFormatList2
Case 14 : vFormato = Excel.XlRangeAutoFormat.xlRangeAutoFormatList3
Case 15 : vFormato = Excel.XlRangeAutoFormat.xlRangeAutoFormat3DEffects 1
Case 16 : vFormato = Excel.XlRangeAutoFormat.xlRangeAutoFormat3DEffects 2
End Select

Ws.Range(Ws.Cells(1, 1), Ws.Cells(Ws.UsedRange.Rows.Count, Ws.UsedRange.Columns.Count)).AutoFormat(vFormato)

pFileName = Path.GetTempFileName.Replace("tmp", "xls")
File.Delete(pFileName)
Exc.ActiveWorkbook.SaveAs(pFileName, Excel.XlTextQualifier.xlTextQualifierNone - 1)
End If
Exc.Quit()

Ws = Nothing
Wb = Nothing
Exc = Nothing

GC.Collect()

If valor > -1 Then
Dim p As System.Diagnostics.Process = New System.Diagnostics.Process
p.EnableRaisingEvents = False
p.Start("Excel.exe", pFileName)
End If
System.Threading.Thread.CurrentThread.CurrentCultu re = vCultura
End Sub

End Class
Esto me exporta el datagrid a excel a la perfección utilizando una .dll de microsoft office (Office XP PIAs). Tengo la .dll para word y access también y me gustaria poder realizar estas exportaciones pero no sé como hacerlo, soy novato en .NET. He intentado modificar las funciones cambiando el Excel por WOrd pero no funciona. Alguien sabe como hacerlo?

Un saludo y gracias
  #2 (permalink)  
Antiguo 03/03/2008, 14:16
 
Fecha de Ingreso: marzo-2008
Mensajes: 3
Antigüedad: 16 años, 2 meses
Puntos: 0
Re: Exportar datagrid a word, access..

Si solo modificas los textos de Excel a Word no va funcionar porque, el código que estas poniendo contiene celdas y filas, cosa que en Word no existe. Pero a ver si este codigo te sirve

Set wrdApp = New Word.Application

'Set to false if you don't want to see the word doc
wrdApp.Visible = True
'Agrega Documento
Set wrdDoc = wrdApp.Documents.Add
wrdDoc.Select

Set wrdSelection = wrdApp.Selection

wrdSelection.ParagraphFormat.Alignment = m_ParaAlign ' Pasas parametros de alienacion
wrdSelection.Font.Name = "Arial" ' Fuente
wrdSelection.Font.Size = m_FontSize ' tmaño de fuenbte
wrdSelection.Font.Bold = m_FontBold ' Si es negrita
wrdSelection.Font.ColorIndex = m_StrColor ' Color de la fuente
wrdSelection.TypeText m_StrToAdd ' Y esta varible contiene el texto a insertar en el documento

Adaptandolo un poco con esto podrias hacer la exportación a word
  #3 (permalink)  
Antiguo 04/03/2008, 06:55
 
Fecha de Ingreso: noviembre-2006
Mensajes: 437
Antigüedad: 17 años, 5 meses
Puntos: 3
Re: Exportar datagrid a word, access..

Muchas gracias oosg2000, pensaba que nadie me podria ayudar.. Luego probaré el codigo que me has pasado y te digo como ha ido. Me gustaria poder utilizar las .dll de Imports Microsoft.Office.Interop para poder exportar a word y access como lo hago con el excel, pero el ejemplo que he puesto es lo unico que he encontrado, sabes de algun tutorial o página donde pueda encontrar como utilizar estas dll?

Un saludo y gracias de nuevo
  #4 (permalink)  
Antiguo 04/03/2008, 11:07
 
Fecha de Ingreso: marzo-2008
Mensajes: 3
Antigüedad: 16 años, 2 meses
Puntos: 0
Re: Exportar datagrid a word, access..

Mira el codigo q te pase es una forma de hacerlo, pero personalmente yo he usado esta forma, a ti tambien te podria ser de utilidad, igual tienes q tener la dll de word agregada al proyecto.

Mira este codigo lo tienes q poner debajo de la etiqueta de title y donde dice Datagrid1 sustituyes por el nombre de tu datagrid:

<title>Handsets</title>
<SCRIPT language=javascript>
function Exportar()
{
//Funcion que exporta a Word el contenido del Grid
var index;
var str;
var sHTML;





//Obtenemos los datos del grid
sHTML = window.document.getElementById('DataGrid1').outerH TML;
var xlApp, xlSheet;
//Crea aplicacion Excel
xlApp = new ActiveXObject("Word.Application");
var oBook = xlApp.Documents.Add();
//Inserta los datos del Grid en el doc de Word
oBook.HTMLProject.HTMLProjectItems(1).Text = sHTML;
oBook.HTMLProject.RefreshDocument();
//Hace visible Word
xlApp.Visible = true;

}
</SCRIPT>

En el formulario agregas un inputbox: q contega la llamada a la funcion por ejemplo:

<input id="BtnExportar" type="submit" value="Exportar" name="BtnExportar" onClick ="Exportar()" runat="server">

Pruebalo y ojala sirva para lo que necesitas.
  #5 (permalink)  
Antiguo 04/03/2008, 12:58
 
Fecha de Ingreso: noviembre-2006
Mensajes: 437
Antigüedad: 17 años, 5 meses
Puntos: 3
Re: Exportar datagrid a word, access..

Hola de nuevo. Mi proyecto es un winform, tu código no me sirve, aunque te doy las grácias por tu respuesta y tu rato estudiando mi caso. Las dll ya las tengo, tanto la de excel como la de word y la de access,las tengo incorporadas al proyecto, el problema es que nosé como utilizarlas.

De nuevo gracias.
Un saludo!
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 16:24.