Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

leonecr

Ler Xls com C# (C Sharp) em Asp.Net 3.5

Recommended Posts

Ola estou tentando fazer um sistema de envio de email no qual e preciso importar um lista de cadastro de emails em Excel com extensão .xls pesquisei como fazer isso e tentei “ler o xls” mas não e da ERRO consegui abaixo o código do script :

To tentando ler e vincular ao DATAGRID mas meu objetivo e incluir no BD

Utilizei como se conectar a um base de banco de dados com o OLEDB.

E tem como utliizar o StreamReader ? e como faz ? ou Outra Classe ou componente que seja simples, facil, rápido e que tenho recursos para validar informações? Pois predento ler o campo e verificar se e campo de nome ou email Como faço essas validações?

Agradeço a todos que me ajudarem.

 

//============= ERRO NA EXECUCAO

System.Data.OleDb.OleDbException: Não foi possível encontrar ISAM instalável. em System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection) em System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) em System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) em System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) em System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) em System.Data.OleDb.OleDbConnection.Open() em LerXls.Page_Load(Object sender, EventArgs e) na d:\web\localuser\crdancas\www\aspnettestes02\LerXls.aspx.cs:linha 53

 

Provider= Microsoft.Jet.OleDb.4.0;data source= @d:\web\LocalUser\crdancas\www\aspnettestes02\arquivos\estoque.xls;Extended Properties=Excel 11.0;HDR=YES;

Select * From [estoque$]

 

 

 

//=============PAGINA ASPX

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="LerXls.aspx.cs" Inherits="LerXls" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http-~~-//www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http-~~-//www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>

   <form id="Form2" method="post" runat="server">
<asp:Label ID="lblSql1" Runat="server" />
<asp:DataGrid ID="dtgAgenda1" Runat="server"
             HeaderStyle-BackColor="Red"
             HeaderStyle-ForeColor="White"
             HeaderStyle-Font-Name="Verdana"
             HeaderStyle-Font-Size="10"
             ItemStyle-BackColor="Cyan"
             ItemStyle-Font-Name="Verdana"
             ItemStyle-Font-Size="10"
             CellPadding="4"
             GridLines="Both" />
             </form>
</body>
</html>

 

 

//============== CODIGO C#

 

 

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data;
using System.Data.OleDb;



public partial class LerXls : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //string cnn = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\preco.xls;Extended Properties='Excel 8.0;HDR=NO;'";
       // string _conectionstring;
       // _conectionstring = @"Provider=Microsoft.Jet.OLEDB.4.0;";
       // _conectionstring += String.Format("Data Source={0};", ConfigurationManager.AppSettings["caminhoExcel"]);
      //  //_conectionstring += "Data Source=" + Server.mappath("~/adm/xls/preço.xls") + ";";
       // _conectionstring += "Extended Properties='Excel 8.0;HDR=NO;'";
       
        string MyProvider = "Microsoft.Jet.OleDb.4.0;";
        //pode em ves de Provider colocar Network Library=DBMSSOCN" indica para a  usar TCP/IP Q238949
        string Mydatasource = "d:\\web\\LocalUser\\crdancas\\www\\aspnettestes02\\arquivos\\estoque.xls;";
        //string usuario = "admin";
        //string senha = "123";
        string AdiconalParamStrConn = "Extended Properties=Excel 11.0;HDR=YES;";

        string strConn = @"Provider= " + MyProvider + ""
                          + "data source= @" + Mydatasource + ""
                          + AdiconalParamStrConn;

        // SQL / Access / Oracle  MySql  
        // "User ID=Admin;" & _
        // "Password=" 
        // string strSql = "Select * From [Sheet1$]";//se o seu Excel for em português será Plan1
        // string strSql = "Select * From [Plan1$]";
        //string strSql = "Select * From [estoque$]";

        string strSql = "Select * From [estoque$]";

        lblSql1.Text = strConn + "<br>" + strSql;
        try
        {
            OleDbConnection cn = new OleDbConnection(strConn);
            cn.Open();
            OleDbCommand cmd = new OleDbCommand(strSql, cn);
            
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            this.dtgAgenda1.DataSource = dt.DefaultView;
            this.dtgAgenda1.DataBind();
            cn.Dispose();
        }
        catch (Exception exc)
        {
            Response.Write(exc.ToString());

        }
        //finally
      ///  {
      //      

       // }

         

    }
}

Compartilhar este post


Link para o post
Compartilhar em outros sites
Ja vi isso mas nao conseguir fazer deu erro tambem.

 

Abaixo ao codigo que testei

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.OleDb;
 


public partial class LerXls2 : System.Web.UI.Page
{
    public DataTable LerExcel()
    {
        string _conectionstring;
        _conectionstring = @"Provider=Microsoft.Jet.OLEDB.4.0;";
        _conectionstring += "Data Source=d:\\web\\LocalUser\\crdancas\\www\\aspnettestes02\\arquivos\\estoque.xls;";
        _conectionstring += "Extended Properties='Excel 8.0;HDR=YES;'";
        
        OleDbConnection cn = new OleDbConnection(_conectionstring);
        OleDbCommand cmd = new OleDbCommand("Select * from [estoque$]", cn);
        
        OleDbDataAdapter da = new OleDbDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);

        try
        {
            cmd.CommandType = CommandType.Text;
            cn.Open();
            cmd.ExecuteReader();
            return dt;
        }
        catch (OleDbException ex)
        {
            throw new Exception(ex.Message.ToString());
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message.ToString());
        }
        finally
        {
            cn.Close();
            cn.Dispose();
            cmd.Dispose();
        }

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        int id;
        string nome;
        double preco; 
        
        try
        {
            LblError.Visible = false;
            LerXls2 lendo = new LerXls2();
            DataTable dt = lendo.LerExcel();
            //lendo.UpdateDb(codigo, estoque, valor);
            //atribui o datatable ao datagridview para exibir o resultado
            dataGridView1.DataSource = dt;
            dataGridView1.DataBind(); //QUANDO FOR WEB
            
            LblError.Text = "SUCESSO";
            LblError.Visible = true;
        }
        catch (Exception ex)
        {
            LblError.Text = ex.Message.ToString();
            LblError.Visible = true;
        }
    }
}

Compartilhar este post


Link para o post
Compartilhar em outros sites

Ola a todos conseguir ler so que agora coloquei junto com o sitema de upload e nao ta dando certo poderia olhar para mim e me falar onde to errando d o seguinte erro "Referência de objeto não definida para uma instância de um objeto."

 

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using DAL;
using DTO;
using MySql.Data.MySqlClient;
using System.IO;
using System.Data.OleDb;



public partial class UpArquivos : System.Web.UI.Page
{
    private string _conexaoMySQL = " RETIREI A STRING DE CONEXAO POR PRIVACIDADE";
    string caminhoArq = "d:\\web\\LocalUser\\crdancas\\www\\aspnettestes01\\uploads\\";
        
    string ArquivoUpado = "";
    string vr_nome;
    string vr_fone;
    int id;
    string nome;
    double preco;

    protected void Page_Load(object sender, EventArgs e)
    {
        //Confirmaçao de envio 
        btnEnviarArq.Attributes.Add("onclick", "javascript:if(confirm('Confirmar Upload do arquivo?')==false)return false;");
        lblMessagem.Text = null;
       // GravarnoBdRegXls();
    }
    
    private void UploadArquivo()
    {
        if (FileUpload1.HasFile)
            try
            {
                FileUpload1.SaveAs(caminhoArq + FileUpload1.FileName);
                string arq = FileUpload1.PostedFile.FileName;
                //verificamos a extensão através dos últimos 4 caracteres
                string extensao = arq.Substring(arq.Length - 4).ToLower();

                lblMessagem.Text = 
                    "Nome do arquivo: "       +  arq + 
                    "<br>Tamanho do arquivo:" + FileUpload1.PostedFile.ContentLength +
                    "<br> Tipo de arquivo: "  + FileUpload1.PostedFile.ContentType   +
                    "<br>Extensao: " + extensao;

                string enderecoUrl = "http://www.crdancas.com.br/app1/uploads/";
                myHLink.NavigateUrl = enderecoUrl + FileUpload1.PostedFile.FileName;

                //Atribuo valor a variavel
                ArquivoUpado = caminhoArq + FileUpload1.PostedFile.FileName;
              
                //// LER O ARQUIVO UPADO
                if (extensao ==  ".xls" )
                {
                    GravarnoBdRegXls();
                }
                if (extensao ==  ".csv" )
                 {
                    LerArquivoCsvTxt();
                }
                //// VERIFICA SE  O ARQUIVO EXISTE E APAGA
                //FileInfo arquivoUp = new FileInfo(ArquivoUpado);
                //if (arquivoUp.Exists)
                //{
                //    arquivoUp.Delete();
                //}

            }
            catch (Exception ex)
            {
                lblMessagem.Text = "ERRO CRITICO NO UPLOAD :" + ex.Message.ToString();
            }
        else
        {
            lblMessagem.Text = null;
        }
    }

    public DataTable LerExcel()
    {
        string _conectionstring;
        string _caminhohArquivo;
        //string _ArquivoXls = "estoque.xls";
        string _ArquivoXls = FileUpload1.PostedFile.FileName;
        
        _caminhohArquivo = caminhoArq + _ArquivoXls + ";";
        
        _conectionstring = @"Provider=Microsoft.Jet.OLEDB.4.0;";
        //_conectionstring += "Data Source=d:\\web\\LocalUser\\crdancas\\www\\aspnettestes02\\arquivos\\estoque.xls;";
        _conectionstring += "Data Source=" + _caminhohArquivo;
        _conectionstring += "Extended Properties='Excel 8.0;HDR=YES;'";
        Response.Write(_conectionstring + "<br>");
        OleDbConnection cn = new OleDbConnection(_conectionstring);
        OleDbCommand cmd = new OleDbCommand("Select * from [estoque$]", cn);

        OleDbDataAdapter da = new OleDbDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);

        try
        {
            cmd.CommandType = CommandType.Text;
            cn.Open();
            cmd.ExecuteReader();
            return dt;
        }
        catch (OleDbException ex)
        {
            throw new Exception(ex.Message.ToString());
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message.ToString());
        }
        finally
        {
            cn.Close();
            cn.Dispose();
            cmd.Dispose();
        }

    }

    private void GravarnoBdRegXls()
    {
        string _caminhohArquivo;
        string _ArquivoXls = FileUpload1.PostedFile.FileName;
        _caminhohArquivo = caminhoArq + _ArquivoXls + ";";
        
        Response.Write(_caminhohArquivo + "<br>");
        
        String sql = "INSERT INTO estoque (nome, preco)" +
                     " VALUES ('" + nome + "'," + preco + ")";
        try
        {
            LblError.Visible = false;
            UpArquivos lendo = new UpArquivos();
            DataTable dt = lendo.LerExcel();

            //atribui o datatable ao datagridview para exibir o resultado
            dataGridView1.DataSource = dt;
            dataGridView1.DataBind(); //QUANDO FOR WEB

            LblError.Text = "LEU COM SUCESSO";
            LblError.Visible = true;
            
            foreach (DataRow DR in dt.Rows)
            {
                nome = DR[1].ToString();
                preco = Convert.ToDouble(DR[2].ToString());
                Response.Write(nome + "  " + preco + "<br>");
                //try
                //{
                //    String sql = "INSERT INTO estoque (nome, preco)" +
                //     " VALUES ('" + nome + "'," + preco + ")";

                //    MySqlConnection con = new MySqlConnection(_conexaoMySQL);
                //    MySqlCommand cmd = new MySqlCommand(sql, con);
                //    con.Open();
                //    cmd.ExecuteNonQuery();
                //    LblError.Text = "SUCESSO AO GRAVAR NO BD ";
                //    con.Close();

                //}
                //catch (Exception ex)
                //{
                //    LblError.Text = "ERRO CRITICO AO GRAVAR NO BD :" + ex.Message.ToString();
                //}
            }


        }
        catch (Exception ex)
        {
            LblError.Text = ex.Message.ToString();
            LblError.Visible = true;
        }
    }
    
    private void LerArquivoCsvTxt()
    {
        try
        {
            ///Para tipo de arquivo CSV ou TXt separado po virgula 
            StreamReader stream = new StreamReader(ArquivoUpado);

            string linha = null;
            while ((linha = stream.ReadLine()) != null)
            {
                string[] linhaSeparada = linha.Split(',');
                vr_nome = linhaSeparada[1];
                vr_fone = linhaSeparada[2];
                
                // Grava no banco de dados os registro lidos do arquivo
                //IncluirRegUp();
                Response.Write(linhaSeparada[0] + "  " + linhaSeparada[1] + "  "+ linhaSeparada[2] + "<br>");
            }

            stream.Close();

        }
        catch (Exception ex)
        {
            lblMessagem.Text = "ERRO CRITICO AO LER CSV :" + ex.Message.ToString();
        }
    }
    
    public void IncluirRegUp()
    {
        String sql =
            "INSERT INTO clientes (nome,fone)" +
            " VALUES ('"+ vr_nome +"','"+ vr_fone +"')";
        try
        {
            
            MySqlConnection con = new MySqlConnection(_conexaoMySQL);
            MySqlCommand cmd = new MySqlCommand(sql, con);
            con.Open();
            cmd.ExecuteNonQuery();
            lblMessagem.Text = "SUCESSO AO GRAVAR NO BD ";
            con.Close();
        }
        catch (Exception ex)
        {
            lblMessagem.Text = "ERRO CRITICO AO GRAVAR NO BD :" + ex.Message.ToString();

        }
    }

    protected void btnEnviarArq_Click(object sender, EventArgs e)
    {
        UploadArquivo();
    }

}

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.