Login Login
MORE

WIDGETS

Widgets

Wanted articles
Who is online?
Article tools

CSharp:Accesso ai files via OLE DB

From Aino Wiki

Jump to: navigation, search

Da Excel a DataTable

        /// <summary>
        /// Crea un DataTable del contenuto del file Excel indicato. Lavora sul primo foglio di lavoro!
        /// </summary>
        /// <param name="fileExcelFullPath">Percorso sul FileSystem del file Excel</param>
        /// <param name="skipFirstLine">Se saltare la prima riga del foglio di lavoro</param>
        /// <param name="text4AllCells">Se considerare testo tutte le colonne del file</param>
        /// <returns></returns>
        public static DataTable GetDataTableFromExcel(string fileExcelFullPath, bool text4AllCells)
        {
            return GetDataTableFromExcel(null, fileExcelFullPath, 0, text4AllCells, 0, 0);
        }
 
        public static DataTable GetDataTableFromExcel(string fileExcelFullPath, bool text4AllCells, int skipFirstNRow)
        {
            return GetDataTableFromExcel(null, fileExcelFullPath, skipFirstNRow, text4AllCells, 0, 0);
        }
 
        public static DataTable GetDataTableFromExcel(string fileExcelFullPath,  bool text4AllCells, int skipFirstNRow, int maxRecord)
        {
            return GetDataTableFromExcel(null, fileExcelFullPath, skipFirstNRow, text4AllCells, maxRecord, 0);
        }
 
 
        /// <summary>
        /// Crea un DataTable del contenuto del file Excel indicato.
        /// </summary>
        /// <param name="workSheetName">Nome del foglio di lavoro. SE NON INDICATO ANDRA' SUL PRIMO foglio di lavoro</param>
        /// <param name="fileExcelFullPath">Percorso sul FileSystem del file Excel</param>
        /// <param name="skipFirstLine">Se saltare la prima riga del foglio di lavoro</param>
        /// <param name="text4AllCells">Se considerare testo tutte le colonne del file</param>
        /// <returns></returns>
        public static DataTable GetDataTableFromExcel(string workSheetName, string fileExcelFullPath, int skipFirstNRow,
                                                        bool text4AllCells, int maxRecord, int headerAtRow)
        {
            bool skipFirstLine = false; // CABLATO DENTRO IN QUANTO questa info è praticamente in       skipFirstNRow            
            string draftHeaderColumns = string.Empty; //Serve solo per capire eventuali errori
            #region DOC
            /* Si son adottati i seguenti driver in quanto garantiscono la compatibilità con Sistema Operativo a 64bit.
               Scaricare ed installare i driver: http://www.microsoft.com/download/en/details.aspx?id=13255
               Se la versione di Office in sviluppo è a 32 bit scaricare:       AccessDatabaseEngine.exe
               Se invece la versione è a 64 bit:                                AccessDatabaseEngine_64.exe
               E' sufficiente installare l'exe sulla macchina di produzione.
 
             Per info su qry string:
             http://www.connectionstrings.com/excel
                 HDR=Yes;   indicates that the first row contains columnnames, not data. "HDR=No;" indicates the opposite.
                 IMEX=1;    tells the driver to always read "intermixed" (numbers, dates, strings etc) data columns as text.
             */
            #endregion
 
            if (!File.Exists(fileExcelFullPath))
            {
                throw new Exception(String.Format("Non trovato il file Excel da elaborare '{0}'.", fileExcelFullPath));
            }
            string sConnectionString = string.Empty;
            DataTable dt = new DataTable();
            OleDbConnection objConn = new OleDbConnection();
            string topMax = string.Empty; //Limite al nr di record restituiti, per ragioni di efficienza nelle preview!
 
            try
            {
                #region Costruzione Query String
 
                string provider = "Microsoft.ACE.OLEDB.12.0";
                string extendPropertyForSpecificFile = "Excel 8.0;"; //Default
                string extExcelFile = Path.GetExtension(fileExcelFullPath);
                switch (extExcelFile.ToLower())
                {
                    case ".xls":
                        provider = "Microsoft.Jet.OLEDB.4.0";
                        extendPropertyForSpecificFile = "Excel 8.0";
                        break;
                    case ".xlsx":
                        extendPropertyForSpecificFile = "Excel 12.0 Xml";
                        break;
                    case ".xlsm":
                        extendPropertyForSpecificFile = "Excel 12.0 Macro";
                        break;
                    case ".xlsb":
                        extendPropertyForSpecificFile = "Excel 12.0";
                        break;
                    default:
                        throw new Exception(String.Format("Tipo di file con estenzione {0} non supportato da questo metodo.", extExcelFile));
                }
                string codeSkipFirstLine = skipFirstLine ? "Yes" : "No";
                string codeText4AllCells = text4AllCells ? "1" : "0";
 
                //EX: string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileExcelFullPath + ";Extended Properties='Excel 8.0;HDR=Yes;'";
                sConnectionString = string.Format("Provider={0};Data Source={1};Extended Properties=\"{2};HDR={3};IMEX={4}\"",
                                                provider, fileExcelFullPath, extendPropertyForSpecificFile, codeSkipFirstLine, codeText4AllCells);
                                                //"Provider=Microsoft.ACE.OLEDB.12.0;" +
                                                //"Data Source=" + fileExcelFullPath + ";" +
                                                //"Extended Properties='" + extendPropertyForSpecificFile + "HDR=" + codeSkipFirstLine + ";IMEX=" + codeText4AllCells + "'";
 
                #endregion
 
                #region Esecuzione della Query sul File
 
                objConn = new OleDbConnection(sConnectionString);
                objConn.Open();
 
                if (string.IsNullOrEmpty(workSheetName))
                {
                    workSheetName = objConn.GetSchema("Tables").Rows[0]["TABLE_NAME"].ToString();
                    workSheetName = workSheetName.Replace("'", string.Empty);
                    workSheetName = workSheetName.Substring(0, workSheetName.Length - 1);
                }
 
                topMax = maxRecord == 0 ? string.Empty : "TOP " + maxRecord;
 
                string qrySQL = string.Format("SELECT {0} * FROM [" + workSheetName + "$]", topMax);
                //string qrySQL = string.Format("SELECT {0} * FROM [" + workSheetName + "]", topMax);
                OleDbCommand objCmdSelect = new OleDbCommand(qrySQL, objConn);
                OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
                objAdapter1.SelectCommand = objCmdSelect;
                objAdapter1.Fill(dt);
 
                #endregion Esecuzione della Query sul File----------------------
 
                //Rimuove le le prime N righe che NON SI VOGLIONO
                if (skipFirstNRow > 0)
                {
                    //strDebug += "Rimosse le seguenti " + skipFirstNRow + " righe.\r\n";
                    for (int i = 0; i < skipFirstNRow; i++)
                    {
                        dt.Rows.RemoveAt(0);
                    }
                }
 
                #region RIDENOMINAZIONE colonne del DataTable già pieno IN BASE alla indicazione o meno della INTESTAZIONE                
                try
                {
                    int nrColumn = dt.Columns.Count;
                    if (headerAtRow > 0)//Caso in cui si è esplicitamente indicata la riga contenente l'intestazione del DataTable
                    {
                        for (int j = 0; j < nrColumn; j++)
                        {
                            draftHeaderColumns += dt.Rows[headerAtRow - 1][j].ToString() + "|";
                            dt.Columns[j].ColumnName = dt.Rows[headerAtRow - 1][j].ToString();
                        }
                        //Rimuove il rigo i cui valori son serviti per l'intestazione
                        dt.Rows.RemoveAt(headerAtRow - 1);
                    }
                    else                //RIDENOMINAZINE standard delle colonne DataTable
                    {
                        for (int j = 1; j <= nrColumn; j++)
                        {
                            dt.Columns[j - 1].ColumnName = "C" + j;
                        }
                    }
                }
                catch (Exception ex)
                {       
                    throw new Exception(string.Format("Errore assegnando l'intestazione dal file Excel, verificare la riga scelta allo scopo.\r\nStralcio dell'intestazione scelta: '{0}'\r\n{1}",
                        draftHeaderColumns, ex.Message));
                }
                #endregion
            }
            catch (Exception ex)
            {
                string strError = "MwC.Libraries.IO.FileManager._GetDataTableFromExcel()\r\n" + ex.Message + "\r\n\r\nConnectionString: '" + sConnectionString + "'";
                throw new Exception(strError);
            }
            finally
            {
                if (objConn.State == ConnectionState.Open)
                {
                    objConn.Close();
                }
            }
            return dt;
        }



C# | Accesso ai files | | Accesso ai files, Excel


Visual Studio | Programmazione

Author