terça-feira, 15 de dezembro de 2015

C# funções para abertura de excel

        #region funções para abertura de excel

        public static DataTable XlsxToDataSet(String pFile, String pNomeAba)
        {
            return XlsxToDataSet(pFile, pNomeAba, VerVersaoExcel(), false);
        }

        public static DataTable XlsxToDataSet(String pFile, String pNomeAba, Boolean pNaoUtilizarImex)
        {
            return XlsxToDataSet(pFile, pNomeAba, VerVersaoExcel(), pNaoUtilizarImex);
        }

        public static DataTable XlsxToDataSet(String pFile, String pNomeAba, Int32 pVersao)
        {
            return XlsxToDataSet(pFile, pNomeAba, pVersao, false);
        }

        public static DataTable XlsxToDataSet(String pFile, String pNomeAba, Int32 pVersao, Boolean pNaoUtilizarImex)
        {
            return XlsxToDataSet_2(pFile, pNomeAba, pVersao, pNaoUtilizarImex, false);
        }

        //http://www.connectionstrings.com/excel-2003/
        /// <summary>
        ///
        /// </summary>
        /// <param name="pFile"></param>
        /// <param name="pNomeAba"></param>
        /// <param name="pVersao"></param>
        /// <param name="pImex">"IMEX=1;" tells the driver to always read "intermixed" (numbers, dates, strings etc) data columns as text. Note that this option might affect excel sheet write access negative.</param>
        /// <returns></returns>
        public static DataTable XlsxToDataSet_2(String pFile, String pNomeAba, Int32 pVersao, Boolean pNaoUtilizarImex, Boolean pSegundaTentativa)
        {
            String extension = string.Empty;
            try
            {
                DataSet ds = new DataSet();
                extension = Path.GetExtension(pFile);
                String iImex = (pNaoUtilizarImex ? "" : "IMEX=1;");

                Boolean iVersaoNova = (pVersao >= 12 && extension.Equals(".xlsx", StringComparison.OrdinalIgnoreCase));
                if (pSegundaTentativa)
                    iVersaoNova = !iVersaoNova;

                OleDbDataAdapter MyCommand;
                //HDR=YES;IMEX=1; //Excel 8.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text // SÓ FUNCIONA COM 'HDR=NO;IMEX=1', MAS 'HDR=NO' FICA SEM O CABEÇALHO NA PRIMEIRA LINHA
                OleDbConnection MyConnection;
                if (iVersaoNova) //12.0 -> Excel 2007
                    MyConnection = new OleDbConnection(String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0;{1}""", pFile, iImex));
                //MyConnection = new OleDbConnection(String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0;""", pFile));
                else
                    MyConnection = new OleDbConnection(String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;{1}""", pFile, iImex));

                MyCommand = new System.Data.OleDb.OleDbDataAdapter(String.Format("SELECT * FROM [{0}$]", pNomeAba), MyConnection);
                MyCommand.TableMappings.Add("Table", "Table");
                MyCommand.Fill(ds);
                MyConnection.Close();

                return ds.Tables[0];
            }
            catch (Exception ex)
            {
                if (pSegundaTentativa || pVersao < 12)
                {
                    if (_ExPrimeiraTentativa == null)
                        _ExPrimeiraTentativa = ex;
                    throw new Exception("Error: " + _ExPrimeiraTentativa.Message.ToString() + Environment.NewLine + Environment.NewLine
                        + "pFile: " + pFile + Environment.NewLine + "pNomeAba: " + pNomeAba + " - pVersao: " + pVersao.ToString() + " - extension: " + extension, ex);
                }
                else
                {
                    _ExPrimeiraTentativa = ex;
                    String iEmail = "seuemail@provedor.com.br";
                    if (ConfigurationManager.AppSettings["email_Erro"] != null)
                        iEmail = ConfigurationManager.AppSettings["email_Erro"].Trim();
                    Email.Enviar("", iEmail, "Erro 1 - Máq: " + WindowsIdentity.GetCurrent().Name + " - Abrir Excel", MontarMsgErro(ex));
                    return XlsxToDataSet_2(pFile, pNomeAba, pVersao, pNaoUtilizarImex, true);
                }
            }
        }
        static Exception _ExPrimeiraTentativa;

        public static DataTable CsvFileToDatatable(string path, bool IsFirstRowHeader)
        {
            string header = "No";
            string sql = string.Empty;
            DataTable dataTable = null;
            string pathOnly = string.Empty;
            string fileName = string.Empty;
            //try
            //{
            pathOnly = Path.GetDirectoryName(path);
            fileName = Path.GetFileName(path);
            sql = @"SELECT * FROM [" + fileName + "]";
            if (IsFirstRowHeader)
            {
                header = "Yes";
            }
            using (OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
            ";Extended Properties=\"Text;HDR=" + header + "\""))
            {
                using (OleDbCommand command = new OleDbCommand(sql, connection))
                {
                    using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
                    {
                        dataTable = new DataTable();
                        //dataTable.Locale = CultureInfo.CurrentCulture;
                        adapter.Fill(dataTable);
                    }
                }
                connection.Close();
            }
            //}
            //finally
            //{
            //}
            return dataTable;
        }

        public static String[] GetExcelSheetNames(string excelFile)
        {
            return GetExcelSheetNames(excelFile, VerVersaoExcel());
        }

        /// <summary>
        /// This mehtod retrieves the excel sheet names from
        /// an excel workbook.
        /// </summary>
        /// <param name="excelFile">The excel file.</param>
        /// <returns>String[]</returns>
        public static String[] GetExcelSheetNames(string excelFile, Int32 pVersao)
        {
            //Stopwatch stopwatch = new Stopwatch();
            //stopwatch.Start();

            OleDbConnection objConn = null;
            DataTable dt = null;

            try
            {
                // Connection String. Change the excel file to the file you will search.
                String connString;
                if (pVersao >= 12) //12.0 -> Excel 2007
                    connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFile + ";Extended Properties=Excel 12.0;";
                else
                    connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";
                // Create connection object by using the preceding connection string.
                objConn = new OleDbConnection(connString);
                // Open connection with the database.
                objConn.Open();
                // Get the data table containg the schema guid.
                dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                if (dt == null)
                {
                    return null;
                }

                String[] excelSheets = new String[dt.Rows.Count];
                int i = 0;

                // Add the sheet name to the string array.
                foreach (DataRow row in dt.Rows)
                {

                    if (!String.IsNullOrEmpty(row["TABLE_NAME"].ToString()) && (row["TABLE_NAME"].ToString().EndsWith("$") ||
                        row["TABLE_NAME"].ToString().EndsWith("$'")))//checks whether row contains '_xlnm#_FilterDatabase' or sheet name(i.e. sheet name always ends with $ sign)
                    {
                        excelSheets[i] = row["TABLE_NAME"].ToString().Replace("$", "").Replace("'", "");
                        i++;
                    }
                }
                excelSheets = excelSheets.Where(x => !string.IsNullOrEmpty(x)).ToArray();

                //// Loop through all of the sheets if you want too...
                //for (int j = 0; j < excelSheets.Length; j++)
                //{
                //    // Query each excel sheet.
                //}

                return excelSheets;
            }
            catch (Exception)
            {
                throw;
                //return null;
            }
            finally
            {
                // Clean up.
                if (objConn != null)
                {
                    objConn.Close();
                    objConn.Dispose();
                    objConn = null;
                }
                if (dt != null)
                {
                    dt.Dispose();
                    dt = null;
                }
                //stopwatch.Stop();
                //MessageBox.Show(stopwatch.Elapsed.ToString());
            }
        }

        public static Int32 VerVersaoExcel()
        {
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            String iVersao = excel.Version;

            // Release the Application object
            excel.Quit();
            excel = null;

            // Collect the unreferenced objects
            GC.Collect();
            GC.WaitForPendingFinalizers();

            //System.Globalization.CultureInfo cultura = new System.Globalization.CultureInfo("pt-BR");
            //System.Threading.Thread.CurrentThread.CurrentCulture = cultura;

            Decimal intVersao = 0;
            Decimal.TryParse(iVersao.Replace(".", ","), out intVersao);
            return Convert.ToInt32(intVersao);
        }

        /// <summary>
        /// This mehtod retrieves the excel sheet names from
        /// an excel workbook.
        /// </summary>
        /// <param name="excelFile">The excel file.</param>
        /// <returns>String[]</returns>
        public static String[] GetExcelSheetNamesOld(string excelFile)
        {
            //Stopwatch stopwatch = new Stopwatch();
            //stopwatch.Start();

            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook wb = excel.Workbooks.Open(excelFile);

            String[] excelSts = new String[wb.Sheets.Count];

            int j = 0;
            foreach (Microsoft.Office.Interop.Excel.Worksheet sheet in wb.Sheets)
            {
                excelSts[j] = (sheet.Name);
                j++;
            }

            // Close the Workbook
            wb.Close();
            wb = null;

            // Release the Application object
            excel.Quit();
            excel = null;

            // Collect the unreferenced objects
            GC.Collect();
            GC.WaitForPendingFinalizers();

            //stopwatch.Stop();
            //MessageBox.Show(stopwatch.Elapsed.ToString());

            return excelSts;
        }

        #endregion

Nenhum comentário:

Postar um comentário