2012-05-04 17 views
9

estoy desarrollando esta sencilla aplicación para cargar un archivo de Excel (.xlsx) e importar los datos presentes en esa hoja de cálculo de Excel en una base de datos de SQL Server Express en .NETCarga de una hoja de Excel e importar los datos en la base de datos de SQL Server

Estoy usando el siguiente código al hacer clic en el botón importar después de navegar y seleccionar el archivo para hacerlo.

protected void Button1_Click(object sender, EventArgs e) 
{ 
     String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True"; 
     //file upload path 
     string path = FileUpload1.PostedFile.FileName; 
     //string path="C:\\ Users\\ Hemant\\Documents\\example.xlsx"; 
     //Create connection string to Excel work book 
     string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;Persist Security Info=False"; 
     //Create Connection to Excel work book 
     OleDbConnection excelConnection = new OleDbConnection(excelConnectionString); 
     //Create OleDbCommand to fetch data from Excel 
     OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection); 
     excelConnection.Open(); 
     OleDbDataReader dReader; 
     dReader = cmd.ExecuteReader(); 
     SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection); 
     //Give your Destination table name 
     sqlBulk.DestinationTableName = "Excel_table"; 
     sqlBulk.WriteToServer(dReader); 
     excelConnection.Close(); 
    } 

Pero el código no se ejecuta cuando uso

string path = FileUpload1.PostedFile.FileName;` 

e incluso

string path="C:\ Users\ Hemant\Documents\example.xlsx";` 

El dReader es incapaz de tomar el camino en este formato.

Sólo es capaz de tomar camino en el siguiente formato

string path="C:\\ Users\\ Hemant\\Documents\\example.xlsx"; 

es decir, con la del \\ en el path.For, que tengo que codificar el camino pero tenemos que buscar el archivo.

Por lo tanto, puede cualquiera, por favor sugerir una solución para utilizar la ruta tomada por el FileUpload1 para importar los datos?

+0

mirada a la cadena de conexión utilizada para SQLExpress. No tienes espacio antes de la carpeta de usuarios. ¿Por qué está poniendo espacios en el camino al archivo Excel? – Steve

Respuesta

13

Usted está tratando con un HttpPostedFile; este es el archivo que se "carga" en el servidor web. Realmente necesita guardar ese archivo en algún lugar y luego usarlo, porque ...

... en su caso, sucede que usted está alojando su sitio web en la misma máquina donde reside el archivo, por lo que la ruta es accesible. Tan pronto como implemente su sitio en una máquina diferente, su código no funcionará.

descomponerlo en dos pasos:

1) Guarde el archivo en algún lugar - es muy común ver esto:

string saveFolder = @"C:\temp\uploads"; //Pick a folder on your machine to store the uploaded files 

string filePath = Path.Combine(saveFolder, FileUpload1.FileName); 

FileUpload1.SaveAs(filePath); 

Ahora que tenemos un archivo local y el trabajo real se puede hacer.

2) Obtener los datos desde el archivo. El código debería funcionar tal cual, pero simplemente hay que escribir la cadena de conexión de esta manera:

string excelConnString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties="Excel 12.0";", filePath); 

entonces se puede pensar acerca de cómo eliminar el archivo que acaba de haber subido y de importación.

Para proporcionar un ejemplo más concreto, podemos refactorizar el código en dos métodos:

private void SaveFileToDatabase(string filePath) 
    { 
     String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True"; 

     String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath); 
     //Create Connection to Excel work book 
     using (OleDbConnection excelConnection = new OleDbConnection(excelConnString)) 
     { 
      //Create OleDbCommand to fetch data from Excel 
      using (OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection)) 
      { 
       excelConnection.Open(); 
       using (OleDbDataReader dReader = cmd.ExecuteReader()) 
       { 
        using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection)) 
        { 
         //Give your Destination table name 
         sqlBulk.DestinationTableName = "Excel_table"; 
         sqlBulk.WriteToServer(dReader); 
        } 
       } 
      } 
     } 
    } 


    private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl) 
    { 


     string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName); 

     fileUploadControl.SaveAs(filePath); 

     return filePath; 

    } 

Simplemente podría entonces llamar SaveFileToDatabase(GetLocalFilePath(@"C:\temp\uploads", FileUpload1));

considerar la revisión de la otra Extended Properties para su cadena de conexión de Excel. ¡Son útiles!

Otras mejoras que puede querer hacer incluyen poner su cadena de conexión de base de datos Sql en config y agregar el manejo de excepciones adecuado. ¡Considere este ejemplo solo para demostración!

+0

Asunto antiguo, pero es muy útil. Probé tu código de demostración. Me dio un error. El error es: "No se pudo encontrar una parte de la ruta 'C: \'. Escribí el archivo en C: unidad. ¿Alguna idea? – Haminteu

+0

@Haminteu el proceso que intenta acceder al archivo puede no tener permiso para leer desde esa ubicación? También me gustaría comprobar la ruta del archivo. – dash

+0

En realidad, ¿qué usuario que está tratando de acceder al archivo? – Haminteu

2

No sé por qué la ruta del archivo no está funcionando, tengo algo de código similar que funciona bien. Pero si con dos "\" funciona, siempre se puede hacer path = path.Replace(@"\", @"\\");

1

trate de usar
cadena de archivo = Path.GetFileName (FileUploadControl.FileName);

A continuación, guarde el archivo en la ubicación especificada utilizando: FileUploadControl.PostedFile.SaveAs (strpath + nombre de archivo);

0
public async Task<HttpResponseMessage> PostFormDataAsync() //async is used for defining an asynchronous method 
    { 
     if (!Request.Content.IsMimeMultipartContent()) 
     { 
      throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 
     } 
     var fileLocation = ""; 
     string root = HttpContext.Current.Server.MapPath("~/App_Data"); 
     MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(root); //Helps in HTML file uploads to write data to File Stream 
     try 
     { 
      // Read the form data. 
     await Request.Content.ReadAsMultipartAsync(provider); 

      // This illustrates how to get the file names. 
      foreach (MultipartFileData file in provider.FileData) 
      { 
       Trace.WriteLine(file.Headers.ContentDisposition.FileName); //Gets the file name 
       var filePath = file.Headers.ContentDisposition.FileName.Substring(1, file.Headers.ContentDisposition.FileName.Length - 2); //File name without the path 
       File.Copy(file.LocalFileName, file.LocalFileName + filePath); //Save a copy for reading it 
       fileLocation = file.LocalFileName + filePath; //Complete file location 
      } 
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, recordStatus); 
      return response; 
} 
catch (System.Exception e) 
    { 
      return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); 
    } 
} 
public void ReadFromExcel() 
{ 
try 
     { 
      DataTable sheet1 = new DataTable(); 
      OleDbConnectionStringBuilder csbuilder = new OleDbConnectionStringBuilder(); 
      csbuilder.Provider = "Microsoft.ACE.OLEDB.12.0"; 
      csbuilder.DataSource = fileLocation; 
      csbuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES"); 
      string selectSql = @"SELECT * FROM [Sheet1$]"; 
      using (OleDbConnection connection = new OleDbConnection(csbuilder.ConnectionString)) 
      using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectSql, connection)) 
      { 
       connection.Open(); 
       adapter.Fill(sheet1); 
      } 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine(e.Message); 
     }   
} 
0

Puede usar OpenXml SDK para archivos * .xlsx. Funciona muy rápido. Hice la implementación simple de C# IDataReader para este SDK. Ver here. Ahora puede importar fácilmente el archivo de Excel a la base de datos del servidor sql usando SqlBulkCopy. método que utiliza memoria pequeña porque lee por SAX (Simple API para XML) (OpenXmlReader)

Ejemplo:

private static void DataReaderBulkCopySample() 
{    
    using (var reader = new ExcelDataReader(@"test.xlsx")) 
    { 
     var cols = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetName(i)).ToArray(); 
     DataHelper.CreateTableIfNotExists(ConnectionString, TableName, cols); 

     using (var bulkCopy = new SqlBulkCopy(ConnectionString)) 
     { 
      // MSDN: When EnableStreaming is true, SqlBulkCopy reads from an IDataReader object using SequentialAccess, 
      // optimizing memory usage by using the IDataReader streaming capabilities 
      bulkCopy.EnableStreaming = true; 

      bulkCopy.DestinationTableName = TableName; 
      foreach (var col in cols) 
       bulkCopy.ColumnMappings.Add(col, col); 

      bulkCopy.WriteToServer(reader); 
     } 
    } 
} 
0
A proposed solution will be: 


protected void Button1_Click(object sender, EventArgs e) 
{ 
     try 
     { 
      CreateXMLFile(); 



     SqlConnection con = new SqlConnection(constring); 
     con.Open(); 

     SqlCommand cmd = new SqlCommand("bulk_in", con); 

     cmd.CommandType = CommandType.StoredProcedure; 

     cmd.Parameters.AddWithValue("@account_det", sw_XmlString.ToString()); 

     int i= cmd.ExecuteNonQuery(); 
      if(i>0) 
      { 
       Label1.Text = "File Upload successfully"; 
      } 
      else 
      { 
       Label1.Text = "File Upload unsuccessfully"; 
       return; 

      } 


     con.Close(); 
      } 
     catch(SqlException ex) 
     { 
      Label1.Text = ex.Message.ToString(); 
     } 




    } 
    public void CreateXMLFile() 
     { 

      try 
      { 
       M_Filepath = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName); 
       fileExtn = Path.GetExtension(M_Filepath); 
       strGuid = System.Guid.NewGuid().ToString(); 
       fNameArray = M_Filepath.Split('.'); 
       fName = fNameArray[0]; 

       xlRptName = fName + "_" + strGuid + "_" + DateTime.Now.ToShortDateString().Replace ('/','-'); 
       fileName = xlRptName.Trim() + fileExtn.Trim() ; 



       FileUpload1.PostedFile.SaveAs(ConfigurationManager.AppSettings["ImportFilePath"]+ fileName); 



       strFileName = Path.GetFileName(FileUpload1.PostedFile.FileName).ToUpper() ; 
       if (((strFileName) != "DEMO.XLS") && ((strFileName) != "DEMO.XLSX")) 
       { 
        Label1.Text = "Excel File Must be DEMO.XLS or DEMO.XLSX"; 
       } 
       FileUpload1.PostedFile.SaveAs(System.Configuration.ConfigurationManager.AppSettings["ImportFilePath"] + fileName); 
       lstrFilePath = System.Configuration.ConfigurationManager.AppSettings["ImportFilePath"] + fileName; 
       if (strFileName == "DEMO.XLS") 
       { 

        strConn = "Provider=Microsoft.JET.OLEDB.4.0;" + "Data Source=" + lstrFilePath + ";" + "Extended Properties='Excel 8.0;HDR=YES;'"; 

       } 

       if (strFileName == "DEMO.XLSX") 
       { 
        strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + lstrFilePath + ";" + "Extended Properties='Excel 12.0;HDR=YES;'"; 

       } 

       strSQL = " Select [Name],[Mobile_num],[Account_number],[Amount],[date_a2] FROM [Sheet1$]"; 



       OleDbDataAdapter mydata = new OleDbDataAdapter(strSQL, strConn); 

       mydata.TableMappings.Add("Table", "arul"); 
       mydata.Fill(dsExcl); 
       dsExcl.DataSetName = "DocumentElement"; 
       intRowCnt = dsExcl.Tables[0].Rows.Count; 
       intColCnt = dsExcl.Tables[0].Rows.Count; 

       if(intRowCnt <1) 
       { 

        Label1.Text = "No records in Excel File"; 
        return; 
       } 
       if (dsExcl==null) 
       { 

       } 
       else 
        if(dsExcl.Tables[0].Rows.Count >= 1000) 
        { 

         Label1.Text = "Excel data must be in less than 1000 "; 
        } 


       for (intCtr = 0; intCtr <= dsExcl.Tables[0].Rows.Count - 1; intCtr++) 
       { 

        if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Name"])) 
        { 
         strValid = ""; 

        } 
        else 
        { 
         strValid = dsExcl.Tables[0].Rows[intCtr]["Name"].ToString(); 
        } 
        if (strValid == "") 
        { 
         Label1.Text = "Name should not be empty"; 
         return; 

        } 
        else 
        { 
         strValid = ""; 
        } 



        if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Mobile_num"])) 
        { 
         strValid = ""; 

        } 
        else 
        { 
         strValid = dsExcl.Tables[0].Rows[intCtr]["Mobile_num"].ToString(); 
        } 
        if (strValid == "") 
        { 
         Label1.Text = "Mobile_num should not be empty"; 

        } 
        else 
        { 
         strValid = ""; 
        } 

        if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Account_number"])) 
        { 
         strValid = ""; 

        } 
        else 
        { 
         strValid = dsExcl.Tables[0].Rows[intCtr]["Account_number"].ToString(); 
        } 
        if (strValid == "") 
        { 
         Label1.Text = "Account_number should not be empty"; 

        } 
        else 
        { 
         strValid = ""; 
        } 





        if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Amount"])) 
        { 
         strValid = ""; 

        } 
        else 
        { 
         strValid = dsExcl.Tables[0].Rows[intCtr]["Amount"].ToString(); 
        } 
        if (strValid == "") 
        { 
         Label1.Text = "Amount should not be empty"; 

        } 
        else 
        { 
         strValid = ""; 
        } 



        if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["date_a2"])) 
        { 
         strValid = ""; 

        } 
        else 
        { 
         strValid = dsExcl.Tables[0].Rows[intCtr]["date_a2"].ToString(); 
        } 
        if (strValid == "") 
        { 
         Label1.Text = "date_a2 should not be empty"; 

        } 
        else 
        { 
         strValid = ""; 
        } 
       } 


      } 
     catch 
      { 

      } 

     try 
     { 
      if(dsExcl.Tables[0].Rows.Count >0) 
      { 

       dr = dsExcl.Tables[0].Rows[0]; 
      } 
      dsExcl.Tables[0].TableName = "arul"; 
      dsExcl.WriteXml(sw_XmlString, XmlWriteMode.IgnoreSchema); 

     } 
     catch 
     { 

     } 
}`enter code here` 
+0

hacer un mejor formateo – Gahan

Cuestiones relacionadas