Transferring Data From Excel to SQL Server Using F#

时间:2015-07-28 15:39:25

标签: sql-server excel f#

I am currently doing a lot of data manipulation in Excel using F# from Visual Studio. I am combining, removing, and modifying tables from various worksheets/workbooks, and am placing the final results into a new workbook. I am well aware that there are various methods of exporting data from an Excel worksheet into Microsoft SQl Server, but I was wondering if there is some library in F# that would support this functionality so that I could code it up in Visual Studio and move the data into a newly created table in SQL Server from there. I have searched the internet, but have not come across anything that describes what I am looking for. If anyone knows if this is possible, or has any idea how this might be accomplished, I would appreciate the help. (I am using SQL Server 2014)

2 个答案:

答案 0 :(得分:0)

听起来Excel type provider正是您所寻找的。

要将数据插入数据库,您可以使用SqlDataConnection type provider,但可能有更好/更简单的方法。

答案 1 :(得分:-1)

You can import your data from Excel to SQL Server just copy and paste from Excel.. but you need to have exactly the same order from Excel to SQL. for example...

If your Excel have 4 columns:

A B C D 1 1 1 1 2 2 2 2 3 3 3 3

Your table must have 4 columns to just copy and paste

ColumnA ColumnB ColumnC ColumnD

In case that you have to many columns and this cannot ordering... you can save your .xls in .csv (delimited comma's) this way you can make import more easy.

you need to read from .cvs with this way

var contents = File.ReadAllText(filename).Split('\n'); var csv = from line in contents select line.Split(',').ToArray();

And then you need to write to your Database:

using(SqlConnection openCon=new SqlConnection("your_connection_String"))
{
  string saveStaff = "INSERT into tbl_staff (staffName,userID,idDepartment) VALUES (@staffName,@userID,@idDepartment)";

  using(SqlCommand querySaveStaff = new SqlCommand(saveStaff))
   {
     querySaveStaff.Connection=openCon;
     querySaveStaff.Parameters.Add("@staffName",SqlDbType.VarChar,30).Value=name;
     .....
     openCon.Open();

     openCon.Close();
   }
 }