martedì 3 maggio 2011

Xls Connector

Ecco un vero e proprio ever green.. Qualcuno tempo fa disse "l'informatica in italia si fa con Excel", se ben ci pensate il più delle volte quest'affermazione è spaventosamente vera.
Se non preoccupante.

Tuttavia è sempre una bella comodità trovarsi un sistema semplice ed efficace per leggere un foglio excel.

Ed ecco che vi presento la mia versione che come sempre è base base, ma torna sempre comoda.

Queste vi servono necessariamente...
using System.Data;
using System.Data.OleDb;


public class XlsConnector
{

public enum ExcelVersion
{
Excel_97,
Excel_2000,
Excel_2010
}

public enum CellValueDirection
{
_input,
_output,
_both
}

public class CellAddres
{
private string _cellAddress;
private CellValueDirection _cellDirection;

public string cellAddress
{
get { return _cellAddress; }
set { _cellAddress = value; }
}

public CellValueDirection cellDirection
{
get { return _cellDirection; }
set { _cellDirection = value; }
}
}

private string _filePath;
private string _fileName;
private ExcelVersion _fileVersion;

private OleDbConnection cnn;

public XlsConnector(string filePath, string fileName, ExcelVersion fileVersion)
{
_fileName = fileName;
_filePath = filePath;
_fileVersion = fileVersion;
}

public bool OpenConnection()
{
try
{
if (
(cnn != null) &&
(cnn.State == ConnectionState.Open)
)
{
cnn.Close();
cnn = null;
}

cnn = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
_filePath + _fileName + ";" +
"Extended Properties=" + FileVersionEx(_fileVersion)
);
cnn.Open();

return true;
}
catch
{
return false;
}
}

public DataTable ReadSheet(string SheetName)
{
try
{
DataTable dtx = new DataTable();
OleDbDataAdapter oda = new OleDbDataAdapter(
"SELECT * FROM [" + SheetName + "$]", cnn
);

oda.Fill(dtx);

oda = null;

return dtx;
}
catch
{
return new DataTable("Empty");
}


}

public bool CloseConnection()
{
try
{

if (
(cnn != null) &&
(cnn.State == ConnectionState.Open)
)
{
cnn.Close();
cnn = null;
}

return true;
}
catch
{
return false;
}
}

private string FileVersionEx(ExcelVersion ev)
{
switch (ev)
{
case ExcelVersion.Excel_97: { return "Excel 97"; }
case ExcelVersion.Excel_2000: { return "Excel 8.0"; }
case ExcelVersion.Excel_2010: { return "Excel 10.0"; }
}

return "Excel 97";
}
}

Nel chiamante vi servirà:

xc.OpenConnection(); (per aprire la connessione)

DataTable dtx = xc.ReadSheet("Foglio1"); ( per selezionare il foglio )

xc.CloseConnection(); (per chiudere la connessione)



xc= null;

Nessun commento: