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

exportar datos a excel

Estas en el tema de exportar datos a excel en el foro de .NET en Foros del Web. 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 ...
  #1 (permalink)  
Antiguo 26/03/2008, 16:40
 
Fecha de Ingreso: febrero-2008
Mensajes: 13
Antigüedad: 16 años, 2 meses
Puntos: 0
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();
}
}
}
  #2 (permalink)  
Antiguo 28/03/2008, 03:40
 
Fecha de Ingreso: febrero-2008
Mensajes: 74
Antigüedad: 16 años, 2 meses
Puntos: 0
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.
  #3 (permalink)  
Antiguo 28/03/2008, 09:29
 
Fecha de Ingreso: febrero-2008
Mensajes: 13
Antigüedad: 16 años, 2 meses
Puntos: 0
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.
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:06.