DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Read And Import An Excel Workbook With CSharp Ver1
// All this code should belong to a class
//Variables privadas para controlar Excel
private Excel.Application objExcel = null;
private Excel.Workbook objWorkbook = null;
private Excel.Worksheet objWorkSheet = null;
private void RecorrerArchivoExcel(string strArchivo, int intHoja)
{
if (this.InicializarExcel())
{
this.AbrirExcelWorkBook(strArchivo, intHoja);
for (int i = 1; i <= 10; i++)
{
string tmp = (string) objWorkSheet.get_Range("J"+i.ToString(), Missing.Value ).Text;
this.lstContenido.Items.Add(tmp);
}
//Cerrar el archivo
objWorkbook.Close(false,null,null);
}
}
private bool AbrirExcelWorkBook(string strArchivo, int intHoja)
{
try
{
//Abrir el workbook
objWorkbook = objExcel.Workbooks.Open(strArchivo, 0, true, 5,
"", "", true, Excel.XlPlatform.xlWindows, "\t", false, false,
0, true,null,null);
// Obtener la coleccion de hojas del workbook
Excel.Sheets sheets = objWorkbook.Worksheets;
// Obtener la hoja necesaria
objWorkSheet = (Excel.Worksheet) sheets.get_Item(intHoja);
//Devolver el control
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
private bool InicializarExcel()
{
try
{
objExcel = new Excel.Application();
// Chekear si el objeto excel pudo ser creado
if (objExcel == null)
{
MessageBox.Show("ERROR: No se pudo ejecutar Microsoft EXCEL");
return false;
}
// Visualizar el objeto excel
objExcel.Visible = false;
//Se logro inicializar el componente Excel
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}





