Regresar   Foros del Web > Programación para sitios web > .NET

El registro es Gratis en Foros del Web
Respuesta
 
Herramientas Buscar en Tema Desplegado
Antiguo 26/03/08, 16:40:25   #1 (permalink)
cjcesar ha deshabilitado el Karma
 
Registrado: feb 2008
Mensajes: 12
cjcesar is offline  
exportar datos a excel

hola, tengo una consulta ojala puedan ayudarme: tengo que guardar datos de un archivo en excel (que tiene como 15 columnas y muchas filas) en un nuevo excel; cuando intento pasar datos al excel no se guarda nada en el archivo que se crea, no me sale ningun error, nada.
Cuando hago el debug, en la variable objQryTables (que es de tipo Excel.QueryTables) dice que se produjo la excepcion: System.Runtime.InteropServices.COMException;

ojala alguien tenga la solucion, gracias; mi codigo:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace escritura
{
public partial class Escritura : Form
{
private Excel.Application objExcel = null;
private Excel.Workbooks objBooks = null;
private Excel._Workbook objBook = null;
private Excel.Sheets objSheets = null;
private Excel._Worksheet objSheet = null;
private Excel.Range objRange = null;
private Excel.Font objFont = null;
private Excel.QueryTables objQryTables = null;
private Excel._QueryTable objQryTable = null;
private object objOpt = System.Reflection.Missing.Value;

private object strRutaAGuardar = "C:\\Documents and Settings\\user\\Escritorio\\lecturaCampos\\";
private string strRuta = "C:\\Documents and Settings\\user\\Escritorio\\lecturaCampos\\Registr os.xls";

public Escritura()
{
InitializeComponent();
}
private void btGuardar_Click(object sender, EventArgs e)
{
guardandoEnExcel();
}
public void guardandoEnExcel()
{
objExcel = new Excel.Application();
objBooks = (Excel.Workbooks)objExcel.Workbooks;
objBook = (Excel._Workbook)objBooks.Add(objOpt);

objSheets = (Excel.Sheets)objBook.Worksheets;
objSheet = (Excel._Worksheet)(objSheets.get_Item(1));
objRange = objSheet.get_Range("A1", objOpt);
objQryTables = objSheet.QueryTables;

objQryTable = (Excel._QueryTable)objQryTables.Add(
"OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
strRuta + ";", objRange, "select Entidad from [Hoja1$]");

objQryTable.RefreshStyle = Excel.XlCellInsertionMode.xlInsertEntireRows;

objBook.SaveAs(strRutaAGuardar + "libro2.xls", objOpt, objOpt,
objOpt, objOpt, objOpt, Excel.XlSaveAsAccessMode.xlNoChange, objOpt, objOpt,
objOpt, objOpt, objOpt);
objBook.Close(false, objOpt, objOpt);
objExcel.Quit();
}
}
}
  Responder Con Cita
Antiguo 28/03/08, 03:40:36   #2 (permalink)
mosanpe ha deshabilitado el Karma
 
Registrado: feb 2008
Mensajes: 33
mosanpe is offline  
Re: exportar datos a excel

Hola!

No se si te sirve de mucho pero aki te envio un trozo de codigo que me encontre.

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 te vuelca todo a excel.

Espero que te sirva de algo.

Un saludo.
  Responder Con Cita
Antiguo 28/03/08, 09:29:04   #3 (permalink)
cjcesar ha deshabilitado el Karma
 
Registrado: feb 2008
Mensajes: 12
cjcesar is offline  
Re: exportar datos a excel

ok, gracias; tambien encontré una solución, lo que hago es leer el archivo en excel con:
OleDbDataAdapter adapter = new OleDbDataAdapter();
OleDbCommand consultaBD = new OleDbCommand(consulta, obtConexionBD()); ...

y luego hago un select para cargar los campos en un Dataset; luego uso un OleDbDataReader para poder leer los datos del archivo.
De que ya lei los datos, los guardo en un objeto List y luego para pasarlos a un nuevo archivo de excel, lo hago celda x celda asi:

public void guardandoEnExcel(List<Datos> registros)
{
objExcel = new Excel.Application();
objBooks = (Excel.Workbooks)objExcel.Workbooks;
objBook = (Excel._Workbook)objBooks.Add(objOpt);

objSheets = (Excel.Sheets)objBook.Worksheets;
objSheet = (Excel._Worksheet)(objSheets.get_Item(1));

objRange = objSheet.get_Range("A1", objOpt );
objRange.set_Value(objOpt, "Hoja Ruta");
objRange = objSheet.get_Range("B1", objOpt);
objRange.set_Value(objOpt, "Documento remitido");
objRange = objSheet.get_Range("C1", objOpt);
objRange.set_Value(objOpt, "Entidad");
objRange = objSheet.get_Range("D1", objOpt);
objRange.set_Value(objOpt, "Sector");
objRange = objSheet.get_Range("E1", objOpt);
objRange.set_Value(objOpt, "Titular");
objRange = objSheet.get_Range("F1", objOpt);
objRange.set_Value(objOpt, "Derivado");
objRange = objSheet.get_Range("G1", objOpt);
objRange.set_Value(objOpt, "Tipo");
objRange = objSheet.get_Range("H1", objOpt);
objRange.set_Value(objOpt, "Ley");
objRange = objSheet.get_Range("I1", objOpt);
objRange.set_Value(objOpt, "DNI");
objRange = objSheet.get_Range("J1", objOpt);
objRange.set_Value(objOpt, "Nº Folios");
objRange = objSheet.get_Range("K1", objOpt);
objRange.set_Value(objOpt, "Observaciones");

for (int m = 0; m < registros.Count; m++)
{ long ind=m+3;
objRange = objSheet.get_Range("A"+ind.ToString() , objOpt);
objRange.set_Value(objOpt, registros[m].HRuta );
objRange = objSheet.get_Range("B" + ind.ToString(), objOpt);
objRange.set_Value(objOpt, registros[m].Doc);
objRange = objSheet.get_Range("C" + ind.ToString(), objOpt);
objRange.set_Value(objOpt, registros[m].Entidad);
objRange = objSheet.get_Range("D" + ind.ToString(), objOpt);
objRange.set_Value(objOpt, registros[m].Sector);
objRange = objSheet.get_Range("E" + ind.ToString(), objOpt);
objRange.set_Value(objOpt, registros[m].Titular);
objRange = objSheet.get_Range("F" + ind.ToString(), objOpt);
objRange.set_Value(objOpt, registros[m].Derivado);
objRange = objSheet.get_Range("G" + ind.ToString(), objOpt);
objRange.set_Value(objOpt, registros[m].TipoPension);
objRange = objSheet.get_Range("H" + ind.ToString(), objOpt);
objRange.set_Value(objOpt, registros[m].Ley);
objRange = objSheet.get_Range("I" + ind.ToString(), objOpt);
objRange.set_Value(objOpt, registros[m].DNI);
objRange = objSheet.get_Range("J" + ind.ToString(), objOpt);
objRange.set_Value(objOpt, registros[m].Folios);
objRange = objSheet.get_Range("K" + ind.ToString(), objOpt);
objRange.set_Value(objOpt, registros[m].Observ);

}

Asi puedo guardar en excel, pero me parece ineficiente porque hay que leer dato x dato de cada fila; lo ideal seria con un select capturar todo del excel y luego enviar todo a otro archivo excel.
Bueno gracias, y si alguien sabe como guardar todo un bloque resultado del select oajla me pueda indicar como modificar el codigo.
  Responder Con Cita
Respuesta


Califica este Tema - exportar datos a excel.

Herramientas Buscar en Tema
Buscar en Tema:

Búsqueda Avanzada
Desplegado Califica este Tema
Califica este Tema:

Reglas del foro
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está activado
Las caritas están activado
Código [IMG] está activado
Código HTML está desactivado


Todas las horas son GMT -6. La hora es 15:06:00.

Message Board Statistics

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95