Solved

How can I allow uploading and mapping of Excel file to relational database?

Posted on 2008-10-03
7
434 Views
Last Modified: 2012-05-05
I've seen some online control panels where you can upload a delimited file, then it takes you to a screen where you can map the column headers of the delimited file to the database column names. How can I do this so I can allow uploading of an Excel file, then the page lists the column headers with a dropdown to the database table columns next to it? I intend on saving that "mapping" to an XML file. I'm using this with an MS SQL 2008 and Access 2007 database. Has anyone done anything like this before?
0
Comment
Question by:bemara57
7 Comments
 
LVL 20

Expert Comment

by:REA_ANDREW
ID: 22633248
Does the file have to be XLS or will or could be CSV.  There may be a license aspect if you want to parse XLS as you need to use Interop and I think you would need a server license for MS OFFICE.  Not sure, but that is what I think.

XLS requires you use the .NET Interop library for excel in office
CSV, is simple string parsing and the top line are generally your headers.

Andrew
0
 
LVL 2

Accepted Solution

by:
jvulliet earned 500 total points
ID: 22633384
Hello,

you can also use OleDb to access your excel file like a database.

Had to make something similar for a project, so wrote a little help class, see code snippet below.

Code is quite self explanatory, but if you need more help don't hesitate to ask.

using System;

using System.Collections.Generic;

using System.Text;

using System.Data.OleDb;

using System.Data;
 

namespace ExcelUtils

{

    public class ExcelFacility

    {

        private string filename;

        private OleDbConnection cnx;
 

        private OleDbConnection getConnection()

        {

            if (cnx == null)

            {

                cnx = new OleDbConnection();

                cnx.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=" + (char)34 + "Excel 8.0;HDR=Yes;" + (char)34;

            }

            return cnx;

        }
 

        /// <summary>

        /// Constructor

        /// </summary>

        /// <param name="filename">Excel file to process</param>

        public ExcelFacility(string filename)

        {

            this.filename = filename;

        }
 

        #region List Tables from spreadsheet

        public List<string> ListTables()

        {

            cnx = getConnection();

            List<string> res = new List<string>();

            try

            {

                cnx.Open();

                DataTable tbl = cnx.GetSchema("Tables");

                foreach (DataRow row in tbl.Rows)

                {

                    res.Add(row["TABLE_NAME"].ToString());

                }

                cnx.Close();

                return res;                

            }

            catch 

            {

                cnx.Close();

                throw;

            }

        }

        #endregion
 

        #region List Columns

        public List<string> ListColumns(string table)

        {

            cnx = getConnection();

            List<string> res = new List<string>();

            try

            {

                cnx.Open();

                DataTable tbl = cnx.GetSchema("COLUMNS");

                foreach (DataRow row in tbl.Rows)

                {

                    if (row["TABLE_NAME"].ToString() == table)

                    {

                        res.Add(row["COLUMN_NAME"].ToString());

                    }

                }

                cnx.Close();

                return res;

            }

            catch

            {

                cnx.Close();

                throw;

            }

        }

        #endregion
 

        #region Get Data in Datatable

        public DataTable GetData(string tbl)

        {

            try 

            {

                string sql = "Select * from [" + tbl + "]";

                OleDbDataAdapter da = new OleDbDataAdapter(sql, getConnection());

                DataSet dst = new DataSet();

                da.Fill(dst);

                cnx.Close();

                return dst.Tables[0];

            } 

            catch 

            {

                cnx.Close();

                throw;

            }

        }

        #endregion

    }

}

Open in new window

0
 
LVL 51

Expert Comment

by:Mark Wills
ID: 22641863
Yep,

can connect to it via a linked server - each table page is then available as if it were a "table"  (advantage can update the spreadsheet)
can connect with openrowset (advantage can manipulate each column as you read it)
can connect with openquery (similar to above)

examples below...  Not exactly sure what the column names with a dropdown is all about - might want to describe that a bit more, along with the XML mapping.




--1) LINKED SERVER
 

-- create a link to that spreadsheet so we can import

EXEC sp_addlinkedserver MyExcel,

     'Jet 4.0',

     'Microsoft.Jet.OLEDB.4.0',

     'c:\ee\My_Test_Spreadsheet.xls', 

      NULL,

     'Excel 5.0;'

GO
 

--Set up login mappings (just ADMIN - jet wants something).

EXEC sp_addlinkedsrvlogin MyExcel, FALSE, NULL, Admin, NULL

GO
 

--List the tables in the linked server (these are the worksheet names) - not needed, but interesting

EXEC sp_tables_ex MyExcel

GO
 

-- now just to make sure we can see the "real" stuff...

select * from myexcel...sheet1$ 
 

-- we can also write back / update that spreadsheet from here just like a table.
 

-- now clean it up...

sp_dropserver 'MyExcel', 'droplogins';

GO
 
 
 

--2) OPENROWSET
 

-- or use openrowset

SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=c:\ee\My_Test_Spreadsheet.xls;HDR=YES', 'SELECT * FROM [sheet1$]')

GO
 
 

--1) OPENDATASOURCE
 

-- or use opendatasource

select * from OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0', 'data source="c:\ee\My_Test_Spreadsheet.xls";Extended properties=Excel 5.0;')...[sheet1$] 

GO

Open in new window

0
Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

 

Author Comment

by:bemara57
ID: 22681879
Thanks for that the help. jvulliet, your script seems like the one I need, but I'm having a run-time error when I try to load up ListColumns(table) into a Grid. My worksheet is called "Worksheet1", so I'm calling ListColumns("Worksheet1$"), but I get this error:

The Microsoft Jet database engine could not find the object ''Worksheet1$'_'.  Make sure the object exists and that you spell its name and the path name correctly.

Do you know what this error means?
0
 
LVL 2

Expert Comment

by:jvulliet
ID: 22681939
Hello, I think you just have to use ListColumns("Worksheet1")  if i remember well.
Does ListTables() works by the way?
Could just be a version issue otherwise (need to change the connection string).
0
 

Author Comment

by:bemara57
ID: 22682023
That's what I initially tried (without the $ at the end), but gave me the identical error:

The Microsoft Jet database engine could not find the object ''Worksheet1$'_'.  Make sure the object exists and that you spell its name and the path name correctly.

Yes, ListTables() work and I get this in the Grid:
-------------------
Item
-------------------
Database
'Worksheet1$'
'Worksheet1$'_

Also, GetData("Worksheet1$") works and populates the Grid with all the records, but GetData("Worksheet1") crashed saying that it can't find the object.

I've read so much confusion about why there are multiple names for the same tab in Excel. I only have one tab worksheet in it.
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
VB.Net How to Exit Sub - Exit Form??? 5 47
C#  Radio button search for Date not DateTime 4 30
SQL Statement to Update Email Domain 2 19
sql Total query 2 14
SQL Server engine let you use a Windows account or a SQL Server account to connect to a SQL Server instance. This can be configured immediatly during the SQL Server installation or after in the Server Authentication section in the Server properties …
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This is a video describing the growing solar energy use in Utah. This is a topic that greatly interests me and so I decided to produce a video about it.

930 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now