How to use an excel file as a database in visual studio using csharp

0

I would like to know how to use an excel file as a database using sharp c in visual studio. This is still not taught to me but I would like to learn to apply it in my university work. I have a book class and a student class that has a book list. The book has the attributes of Title, Author, Code and Area. Now I would like to upload the data of an excel file that looks like this:

There I would have 2 books and I would like to add those books as two objects of the book class to be able to have them in the program without having to create books, just take them out of the document. How could I execute it? Thanks.

    
asked by David Zaplana 17.05.2018 в 04:30
source

3 answers

0

You can use OleDb

For example;

Select

//Definis la ruta
String filename=@"D:\dem.xlsx";  
//Definis el connectionString
String connection=@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+filename+";Extended Properties=\"Excel 12.0 Xml;HDR=YES;\""; 
//Definis la Query 
String Command="Select * from [sheets$]";  
//Instancias un nuevo objeto de tipo OleDbConnection y abris la conexión con .Open();
OleDbConnection con=new OleDbConnection(connection);  
con.Open();  
//Definisun Command pasándole tu query y el objeto de conexión
OleDbCommand cmd=new OleDbCommand(Command,con);  
//Por último creas un Adapter y se lo asignas a un DataTable
OleDbDataAdapter db=new OleDbDataAdapter(cmd);  
DataTable dt=new DataTable();  
db.Fill(dt);  
//Ahora ya tenes acceso a la información del documento excel, podes, por ejemplo, asignarla como DataSource de un dataGridView
dataGridView1.DataSource=dt; 

Insert

//Definis la ruta
String filename=@"D:\dem.xlsx"; 
//Definis el connectionString
String connection=@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+filename+";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";   
//Definis tu Insert
String Command="insert into [sheets$](Codigo,Titulo, Autor, Area) values('valor_codigo','valor_titulo', 'valor_autor', valor_area)";
//Instancias un OleDbConnection y abris la conexión.
OleDbConnection con=new OleDbConnection(connection);  
con.Open();   
//Por último, creas el comando y lo ejecutas
OleDbCommand cmd=new OleDbCommand(Command,con);  
cmd.ExecuteNonQuery();  

I hope it's what you were looking for!

    
answered by 17.05.2018 в 06:09
0

First I can suggest that you use Integration Services to do scheduled tasks to update your BD but if you want to do a routine through programming I suggest this code:

string ExcelContentType = "application/vnd.ms-excel"; 
string Excel2010ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
if (FileUpload1.HasFile) 
{ 
    //verifica el contenido del archivo 
    if(FileUpload1.PostedFile.ContentType==ExcelContentType || FileUpload1.PostedFile.ContentType==Excel2010ContentType) 
    { 
        try 
        { 
            //Guarda la ruta del archivo 
            string path = string.Concat(Server.MapPath("~/TempFiles/"), FileUpload1.FileName); 
            //Guarda el archivo en un temporal 
            FileUpload1.SaveAs(path); 
            //ejemplo de la ruta del archivo  = @"C:\Users\Johnney\Desktop\ExcelData.xls"; 
            string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path); 

            // se conecta a la base de datos obtiene la hoja del excel y selecciona el que quieras 
            using (OleDbConnection connection = 
                         new OleDbConnection(excelConnectionString)) 
            { 
                OleDbCommand command = new OleDbCommand 
                        ("Select * FROM [Sheet1$]", connection); 

                connection.Open(); 

                // empieza a generar un datareader
                using (DbDataReader dr = command.ExecuteReader()) 
                { 

                    // tu conexion de base de datos 
                    string sqlConnectionString = @"Data Source=.\sqlexpress;Initial Catalog=ExcelDB;Integrated Security=True"; 

                    // Copia la data a la base de datos 
                    using (SqlBulkCopy bulkCopy = 
                               new SqlBulkCopy(sqlConnectionString)) 
                    { 
                        bulkCopy.DestinationTableName = "Employee"; 
                        bulkCopy.WriteToServer(dr); 
                        Label1.Text = "los datos fueron recibidos exitosamente"; 
                    } 
                } 
            } 
        } 

        catch (Exception ex) 
        { 
            Label1.Text = ex.Message; 
        } 
    } 
}
    
answered by 17.05.2018 в 06:43
0

Pass OLE, or the classes that you install office (interop). Use one of the many libraries that allow you to read and write data from and to excel, without being tied to need the machine has excel installed.

An example of a library is LinqToExcel, you can find it here: link allows you to search easily and especially with compiler support (strong typed).

Another example is EPPlus, which you find here: link

    
answered by 17.05.2018 в 17:05