从Excel文件将数据插入SQL Server数据库

时间:2017-04-08 14:12:32

标签: c# sql-server excel wcf

我尝试使用excel文件将数据插入数据库。这段代码对我来说很好。但我用这个窗体应用程序。如何将此代码更改为WCF?我需要使用Windows窗体应用程序打开Excel文件,然后将值传递给WCF服务以将数据插入数据库。我怎么能这样做?

private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog opn = new OpenFileDialog();
    opn.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";

    if (opn.ShowDialog() == DialogResult.Cancel)
        return;

    try { 
        FileStream strm = new FileStream(opn.FileName, FileMode.Open);
        IExcelDataReader excldr = ExcelReaderFactory.CreateOpenXmlReader(strm);

        DataSet rslt = excldr.AsDataSet();

        DataClasses1DataContext conn = new DataClasses1DataContext();

        foreach (DataTable table in rslt.Tables)
        {
            foreach (DataRow dr in table.Rows)
            {
                tblExcel addTbl = new tblExcel()
                                  {
                                    SID = Convert.ToString(dr[0]),
                                    Name = Convert.ToString(dr[1]),
                                    Address = Convert.ToString(dr[2])
                                  };
                conn.tblExcels.InsertOnSubmit(addTbl);
            }
        }

        conn.SubmitChanges();

        excldr.Close();
        strm.Close();

        MessageBox.Show("successfully");
    }
    catch (IOException x)
    {
        MessageBox.Show(x.Message);
    }
}

2 个答案:

答案 0 :(得分:2)

以下是创建WCF服务的方法。

做出假设: 假设您有一个tblExcel对象列表,您希望从问题中显示的WinForm客户端应用程序发送到WCF服务。

第1步: 创建一个新的类库项目并将其命名为ExcelDataService 在此项目中,创建一个名为“DataContracts”的新文件夹,并在此文件夹下创建一个具有以下定义的新类:

[DataContract]
public class ExcelData
{
    [DataMember]
    public string Sid { get; set; }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public string Address { get; set; } 
}

注意:tblExcel重命名为ExcelData,该类的定义与您在原始问题中发布的相同。

第2步: 在ExcelDataService项目下创建另一个名为“ServiceContracts”的文件夹,并使用以下定义创建一个新接口

[ServiceContract]
public interface IExcelDataService
{
    [OperationContract]
    bool SaveData(List<ExceData> data);
}

第3步: 接下来创建另一个文件夹并将其命名为“Services”,并使用以下定义创建一个新类

public class ExcelDataService : IExcelDataService
{
    public bool SaveData(List<ExceData> data)
    {

        // Showing the code how to save into SQL is beyond this question.
        // In the data object you have the list of excel data objects that you can save into the sql server
        // you can use Enterprise Library Data block or ADO.Net to save this data into the SQL Server.

    }
}

步骤4a: 现在,在visual studio解决方案中添加一个新项目并将其命名为ExcelDataServiceConsoleHostManager,将项目类型设置为Console Application。在Main方法中,编写以下代码:

using (ServiceHost host = new ServiceHost(typeof(ExcelDataService)))
{
     PrintEndpoints(host.Description);
     host.Open();
     Console.WriteLine("Service(s) are up and running... Press Enter key to exit!");
     Console.ReadLine();
}

步骤4b: 使用以下定义添加另一个静态方法:

 static void PrintEndpoints(ServiceDescription desc)
        {
            Console.WriteLine(desc.Name);
            foreach (ServiceEndpoint nextEndpoint in desc.Endpoints)
            {
                Console.WriteLine();
                Console.WriteLine(nextEndpoint.Address);
            }
        }

第5步: 在此项目的App.config文件中,添加以下配置:

<system.serviceModel>
    <services>
      <service name="ExcelDataService.Services.ExcelDataService">
        <endpoint address="net.tcp://localhost:8887/ExcelDataService/"
                   binding="netTcpBinding"
                   contract="ExcelDataService. ServiceContracts.IExcelDataService"
                  ></endpoint>
      </service>
    </services>
  </system.serviceModel>

确保将所有引用添加到项目中。构建成功后,按F5键启动Excel Data Service Console主机管理器。

下一步是修改客户端应用程序:

第6步: 在客户端应用程序中添加“ExcelDataService.dll”的引用。 使用以下定义创建一个新类:

public class ExcelDataServiceClient : ClientBase<IExcelDataService>
{
    public bool SaveData(List<ExcelData> excelData)
    {
        base.Channel.SaveData(excelData);
    }
}

第7步: 将app.config文件添加到您的客户端(如果尚未添加)并粘贴以下配置

  <system.serviceModel>
    <client>
      <endpoint address="net.tcp://localhost:8887/ExcelDataService/"
                 binding="netTcpBinding"
                 contract="ExcelDataService. ServiceContracts.IExcelDataService"></endpoint>
    </client>
  </system.serviceModel>

保存所有文件并解析所有引用(WCF使用System.ServiceModel.dll)。

第8步: 接下来创建一个ExcelDataServiceClient类的新实例,并调用其实例方法SaveData。

我会将来自客户端的调用包装到try-catch块中以捕获任何异常。

编辑2: 要将文件发送到WCF服务,我们有

客户端将用于发送文件的请求类...

 [DataContract]
 public class UploadFileRequest
 {
       public string FileName { get; set; }
       public string Path { get; set; }
       public byte[] FileContents { get; set; }
 }

以及服务将发回的响应类:

[DataContract]
public class UploadFileResponse
{
     public string Message { get; set; }
}

向IExcelDataService接口添加另一个方法:

 [OperationContract]
 UploadFileResponse UploadFile(UploadFileRequest request);

及其在ExcelDataService类中的实现:

public UploadFileResponse UploadFile(UploadFileRequest request)
{
// In the request object you have the file as byte array that can be used here.             
}

在客户端,在ExcelDataServiceClient类中添加此方法

public string UploadFile(byte[] fileContent, string fileName = "", string filePath = "")
{
    UploadFileRequest request = new UploadFileRequest()
    {
         FileContents = fileContent, FileName = fileName, Path = filePath
    };

    UploadFileResponse response =  base.Channel.UploadFile(request);

    return response.Message;
}

接下来,使用此客户端类的实例调用UploadFile方法并传入参数。

希望这有帮助!

答案 1 :(得分:0)

以下是您可以考虑的两个选项。

private void button4_Click(object sender, EventArgs e)
{
    BindGrid();
}

protected void BindGrid()
{
    string path = "C:\\Users\\Excel\\Desktop\\Coding\\DOT.NET\\Samples C#\\Export DataGridView to SQL Server Table\\Import_List.xls";
    string jet = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0", path);
    OleDbConnection conn = new OleDbConnection(jet);
    OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", conn);
    DataTable dt = new DataTable();
    da.Fill(dt);

    dataGridView1.DataSource = dt;
    BulkUpload();
}

    protected void BulkUpload()
    {
        DataTable dt = (DataTable)dataGridView1.DataSource;
        string connection = "Data Source=excel-pc;Initial Catalog=Northwind.MDF;Trusted_Connection=True;";

        using (var conn = new SqlConnection(connection))
        {
            List<string> errors = new List<string>();
            try{

                conn.Open();
                using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn))
                {
                    bulkCopy.ColumnMappings.Add(0, "Fname");
                    bulkCopy.ColumnMappings.Add(1, "Lname");
                    bulkCopy.ColumnMappings.Add(2, "Age");

                    bulkCopy.BatchSize = 10000;
                    bulkCopy.DestinationTableName = "Import_List";
                    bulkCopy.WriteToServer(dt.CreateDataReader());
                }
            }
            catch (Exception e)
            {
                errors.Add("Error: " + e.ToString());
            }
            finally
            {
                conn.Dispose();
            }
        }
    }

ALSO

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Configuration;
using System.Data.SqlClient;

请记住,你需要在顶部。

package com.mm.android.uamp.model;

import android.support.v4.media.MediaMetadataCompat;
import android.util.Log;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.mm.android.uamp.utils.LogHelper;

import java.util.ArrayList;
import java.util.Iterator;

public class RemoteJSONSource implements MusicProviderSource {

private static final String TAG = LogHelper.makeLogTag(RemoteJSONSource.class);

DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mMusic = mRootRef.child("music");

ArrayList<MediaMetadataCompat> tracksFromFB = new ArrayList<>();
public void buildFromFirebase(){

    mMusic.addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot music : dataSnapshot.getChildren()){

                String title = music.child("title").getValue(String.class);
                String album = music.child("album").getValue(String.class);
                String artist = music.child("artist").getValue(String.class);
                String genre = music.child("genre").getValue(String.class);
                String source = music.child("source").getValue(String.class);
                String id = String.valueOf(source.hashCode());
                String iconUrl = music.child("image").getValue(String.class);
                int trackNumber = music.child("trackNumber").getValue(Integer.class);
                int totalTrackCount = music.child("totalTrackCount").getValue(Integer.class);
                int duration = music.child("duration").getValue(Integer.class);

                MediaMetadataCompat theMetadataFB = new MediaMetadataCompat.Builder()
                        .putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, id)
                        .putString(MusicProviderSource.CUSTOM_METADATA_TRACK_SOURCE, source)
                        .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, album)
                        .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, artist)
                        .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration)
                        .putString(MediaMetadataCompat.METADATA_KEY_GENRE, genre)
                        .putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, iconUrl)
                        .putString(MediaMetadataCompat.METADATA_KEY_TITLE, title)
                        .putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, trackNumber)
                        .putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, totalTrackCount)
                        .build();

                tracksFromFB.add(theMetadataFB);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
        }
    });
}

@Override
public Iterator<MediaMetadataCompat> iterator() {
    buildFromFirebase();
    ArrayList<MediaMetadataCompat> tracksFB = tracksFromFB;

    return tracksFB.iterator();
}

}