CLR: .Net / Mono / Boo / Otros CLR > C#
Generar un archivo excel
(1/1)
cachorro:
Saludos a todos, alguien sabe como se puede generar un archivo de excel con los datos que yo de pase o que tome desde una grilla, me urge hacer esto espero alguiem me pueda ayudar...
edwin_orlando83:
yo hice una clase pero no esta muy estructurada
using System;
using System.Drawing;
namespace Utilidades
{
/// <summary>
/// Description of C_EXCEL.
/// </summary>
public class C_EXCEL
{
public C_EXCEL()
{
}
public void PasarAexcel(System.Windows.Forms.DataGridView dataGridView1, string mensaje )
{
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;
try
{
if( dataGridView1.Rows.Count > 0)
{
oXL = new Excel.Application();
oXL.Visible = false;
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Type.Missing));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
oSheet.get_Range("A3", "D3").Font.Bold = true;
oSheet.Cells[3, 2] = mensaje;
int jv = 1;
foreach (System.Windows.Forms.DataGridViewColumn c in dataGridView1.Columns)
{
if( c.Visible)
{
oSheet.Cells[4, jv] = c.HeaderText;
int fila = 5;
foreach( System.Windows.Forms.DataGridViewRow r in dataGridView1.Rows)
{
oSheet.Cells[fila++, jv] = r.Cells[c.Name].Value;
}
jv++;
}
}
jv=1;
oRng = oSheet.get_Range("I1", "N1");
oRng.EntireColumn.AutoFit();
System.Windows.Forms.MessageBox.Show("Se Exporto a Excel sin Problemas.nEl archivo se abrira automaticamente");
oXL.Visible = true;
oXL.UserControl = true;
}
else
System.Windows.Forms.MessageBox.Show("No hay datos para exportar a Excel","Error");
}
catch (Exception theException)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);
System.Windows.Forms.MessageBox.Show(errorMessage, "Error");
}
}
}
}
utilizo las librerias del office 2003
cachorro:
gracias lo voy a probar, pero hay que habilitar algun using o solo con ese codigo funciona..gracias de antemano..
eversm:
me parece que tmb se puede hacer con conexion ODBC al excel, me encontre este codigo en la web
--- Código: C# --- String sConnectionString = "Provider=MSDASQL;Driver={Microsoft ExcelDriver(*.xls)};DBQ=c:\temp\Sale_Test.xls;;;Exten dedProperties=Excel10.0;HDR=No;"; // Create connection object by using the preceding connection string. objConn = new OdbcConnection(sConnectionString); OdbcCommand objCmdSelect =new OdbcCommand(); objCmdSelect.Connection = objConn; objCmdSelect.CommandText = "Select * From [Week1$]"; objConn.Open();
igual y te sirve
Navegación
Ir a la versión completa