Función para exportar de manera rápida y eficiente, el resultado de una sentencia SQL a una hoja de Excel. Para la versión 5.0 hay que tener instalado un Microsoft Excel de 64 bits.
Código VB6:
Function PasarSqlAExcel(aColumnas, aFrom, aWhere, aFichero,aPagina)
Dim oExcel 'As Object
Dim oBook 'As Object
Dim oSheet 'As Object
Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Add
Set oSheet = oBook.Worksheets(1)
oSheet.Name = aPagina
lSQL = "Select " & aColumnas & " From " & aFrom & " " & aWhere
Dim oQryTable 'As Object
Set oQryTable = oSheet.QueryTables.Add("OLEDB;" & gCn.ConnectionString,
oSheet.Range("A1"), lSQL)
oQryTable.Refresh False
oBook.SaveAs aFichero, 18
oBook.Close
oExcel.Quit
Set oExcel = Nothing
PasarSqlAExcel = True
Exit Function
End FunctionCódigo C#:
using Ahora.Excel;
using AhoraCore;
using AhoraOCX;
using AhoraSistema;
using System;
using System.Windows.Forms;
namespace AhoraScriptsPantalla
{
public class AhoraCl_frmPedidos : AhoraOCX.AhoraBaseScript
{
public void Show()
{
PasarSqlAExcel("*", "Clientes_Datos", "", "C:\\Temp\\TT.xls", "TEST");
}
public bool PasarSqlAExcel(string aColumnas, string aFrom, string aWhere, string aFichero, string aPagina)
{
try
{
IExcelApplication oExcel = AhoraCore.AhoraServiceLocator.Current.GetService<Ahora.Excel.IExcelApplication>();
IExcelWorkbook oBook = oExcel.Workbooks.Add();
IExcelWorksheet oSheet = oBook.Worksheets[1];
oSheet.Name = aPagina;
string lSQL = "SELECT " + aColumnas + " FROM " + aFrom + " " + aWhere;
IExcelQueryTable oQryTable = oSheet.QueryTables.Add("OLEDB;" + gCn.ConnectionString, oSheet.get_Range("A1"), lSQL);
//oQryTable.FieldNames = false; //con esta propiedad se exportan los datos sin los nombres de columna
oQryTable.Refresh(false);
oBook.SaveAs(aFichero, 18);
oBook.Close();
oExcel.Quit();
oExcel = null;
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
}
}¿Le ha sido útil este artículo?
¡Qué bien!
Gracias por sus comentarios
¡Sentimos mucho no haber sido de ayuda!
Gracias por sus comentarios
Sus comentarios se han enviado
Agradecemos su esfuerzo e intentaremos corregir el artículo