Home » excel » c# – Is it possible to set foreign key between two excel sheets?

c# – Is it possible to set foreign key between two excel sheets?

Posted by: admin April 23, 2020 Leave a comment


Is it possible to set foreign key between two excel sheets and query records from the two sheets?

I got an excel sheet of Student Details and another sheet consists of the total marks. Fields common to both the sheet is the RegID. I need to display the Name and Marks from the two sheets on a grid…How can it be done? please help….

Query = “SELECT Status from [Viewer$] as a LEFT JOIN [UI$] as b ON a.[Responsible Person] = b.[Responsible Person] where b.[Responsible Person] = null” ;

This query is not returning the records to a dataset…

How to&Answers:

If you mean to read Data from two Sheets and mix it to make “combined” records which you enter in the Database where you have the FK set then it should be possible.

Read Reading Excel Cells using C#

You can open who sheets which you access in a Loop, but you will have to coordinate the Data building from your sheets.



I’ve used the excel 2007 openxml sdk (DocumentFormat.OpenXml) to great effect in this scenario. It’s basically a LINQ library that takes the excel docs into objects and allows you to query inside c# just like any other LINQ object. Microsoft actually do have (after a quick search) a pretty good ‘idiots guide’ on this topic. You can find it here:

[edit] – added a few more links




if you use LINQ, it’s a no brainer and is definately the only way that I would go with this type of task. It will also ‘cater’ for you idea of fk’s as it will allow you to ‘join’ on any arbitary field that you care to define (i.e. as with any LINQ query), thus it should address your requirement perfectly.


Not possible using SQL. Neither UNIQUE nor FOREIGN KEY is supported where the data source is an Excel workbook.