Import Excel to Sql Server C#

Asked

Viewed 1,790 times

5

I need to import a file excel for a table SQL. However, I need to pick up the lines and go between them because it won’t be all the information I will get from excel. I have exactly what I need but catching TXT file, however the information that I will need to take excel are the same. I wanted to adapt this code to Excel.

My code with txt file:

public void importarTXTtoSQL()
        {
            double vair = 0;
            int counter = 0;

            string path = Server.MapPath("importados/" + Label2.Text);
            // System.IO.StreamReader file = new System.IO.StreamReader(path);
            string[] colunas;
            double cont = 2;
            double var2 = 10000;

            vair = 49 / var2;
            string[] lines = System.IO.File.ReadAllLines(path);

            int numero_linha = 0;

            foreach (string line in lines)
            {
                // Use a tab to indent each line of the file.
                // l.Text+=("\t" + line);

                numero_linha++;

                string linha = line;

                linha = line.Replace("'", "");

                if (numero_linha > 1)
                {
                    int tamanho_linha = line.Length;

                    string comeco_linha = linha.Substring(4, 4);
                    if (comeco_linha == "4468")
                    {
                        string numero_tel = "";
                        string data_ligacao = "";
                        string[] uf;
                        string cod_operadora = "";
                        string numero_tel_chamado = "";
                        string duracao = "";
                        string descricao_categoria = "";
                        string horario_ligacao = "";
                        string valor_ligacao = "";

                        colunas = linha.Split(';');

                        if (colunas.Length > 7)
                        {
                            data_ligacao = inverte2(colunas[29]);
                            descricao_categoria = colunas[30];
                            cod_operadora = colunas[7];
                            numero_tel = colunas[8];
                            horario_ligacao = colunas[36];
                            numero_tel_chamado = colunas[35];
                            duracao = colunas[37];
                            valor_ligacao = colunas[39];

                            uf = descricao_categoria.Split('/');

                            string strsql = "";

                            strsql = "INSERT INTO [SISTEMAS].[dbo].[TEMP_TELEFONIA] " +
                    "([ITEM0],[ITEM1],[ITEM2] ,[ITEM3] ,[ITEM4],[ITEM5],[ITEM6],[ITEM7])" +
              "VALUES('" + data_ligacao + "','" + horario_ligacao + "','" + numero_tel + "','" + descricao_categoria + " Cód. Operadora: " + cod_operadora + "','" + uf[1] + "','" + numero_tel_chamado + "','" + duracao + "','" + valor_ligacao + "')";


                            string strconn = ConfigurationManager.ConnectionStrings["ConnIntranet"].ConnectionString;
                            SqlConnection objConn = new SqlConnection(strconn);
                            try
                            {
                                SqlCommand objCMD2 = new SqlCommand(strsql, objConn);
                                SqlDataReader objInserir;

                                objConn.Open();
                                objInserir = objCMD2.ExecuteReader();
                                objConn.Close();

                                if (cont >= 49)
                                {
                                    cont = 49;
                                }
                                else
                                {
                                    cont = cont + vair;
                                    Session["Status"] = cont;
                                }
                            }
                            catch (Exception erro)
                            {
                                if (objConn.State == ConnectionState.Open)
                                {
                                    objConn.Close();
                                }
                                lblaviso.Text = "Erro ao Salvar o arquivo - " + erro;
                            }
                        }
                    }

                    counter++;
                }
            }
        }

How can I do that ?

My code so far with excel:

public void ImportarExceltoSQL()
        {
                string path = Server.MapPath("importados/" + Label2.Text);
                System.IO.StreamReader file = new System.IO.StreamReader(path);

                Microsoft.Office.Interop.Excel.Application appExcel;
                Microsoft.Office.Interop.Excel.Workbook workbook;
                Microsoft.Office.Interop.Excel.Range range;
                Microsoft.Office.Interop.Excel._Worksheet worksheet;

                appExcel = new Microsoft.Office.Interop.Excel.Application();
                workbook = appExcel.Workbooks.Open(path, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                worksheet = (Microsoft.Office.Interop.Excel._Worksheet)workbook.Sheets[1];
                range = worksheet.UsedRange;

                int rowCount = range.Rows.Count;
                int colCount = range.Columns.Count;
}
  • Maybe this gives you a light while you do not have an answer, it puts the excel data in a datatable that is very easy to navigate: http://www.aspsnippets.com/Articles/Read-and-Import-Excel-File-into-DataSet-or-DataTablusing-C-and-VBNet-ASPNet.aspx

  • @Mauricioferraz I saw this already but it didn’t help me, man at this point I’m stuck on how to go through the excel lines, you know how I can do ?

1 answer

6


Using the package Nuget Epplus:

var arquivo = new FileInfo(Server.MapPath("importados/" + Label2.Text));

using (var package = new ExcelPackage(arquivo))
{
    // Obtendo o Workbook
    var workbook = package.Workbook;
    if (workbook != null)
    {
        if (workBook.Worksheets.Count > 0)
        {
            // Obtendo a primeira página do Workbook
            var primeiraPlanilha = workbook.Worksheets.First();

            // Lendo a primeira célula
            object primeiraCelula = primeiraPlanilha.Cells[1, 1].Value;

            /* Coloque sua lógica aqui */ 
        }
    }
}

In your case, it would be something like this:

    public void importarTXTtoSQL()
    {
        var arquivo = new FileInfo(Server.MapPath("importados/" + Label2.Text));

        using (var package = new ExcelPackage(arquivo))
        {
            // Obtendo o Workbook
            var workbook = package.Workbook;
            if (workbook != null)
            {
                if (workBook.Worksheets.Count > 0)
                {
                    var primeiraPlanilha = workbook.Worksheets.First();

                    for (int i = 1; i < worksheet.Dimension.End.Row; i++)
                    {
                        data_ligacao = inverte2(primeiraPlanilha.Cells[i, 29].Value);
                        descricao_categoria = primeiraPlanilha.Cells[i, 30];
                        cod_operadora = primeiraPlanilha.Cells[i, 7];
                        numero_tel = primeiraPlanilha.Cells[i, 8];
                        horario_ligacao = primeiraPlanilha.Cells[i, 36];
                        numero_tel_chamado = primeiraPlanilha.Cells[i, 35];
                        duracao = primeiraPlanilha.Cells[i, 37];
                        valor_ligacao = primeiraPlanilha.Cells[i, 39];

                        /* E assim por diante */
                    }
  • To using webforms. There is a dll with this Epplus ?

  • I have a logic made here but it is with TXT file. I wanted to use the same logic but with Excel file, because the fields that I will have to adapt to the table in SQL are the same, so I will have to cut the excel line instead of txt. I can put my code here ?

  • There is. Only download from their website: http://epplus.codeplex.com/

  • Expand the example a little.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.