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

问题描述:

我试图用Excel文件插入数据到数据库。这段代码适合我。但我使用Windows窗体应用程序。我如何将此代码更改为WCF?我需要使用Windows窗体应用程序打开Excel文件,然后将值传递给WCF服务以将数据插入数据库。我怎样才能做到这一点?从Excel文件插入数据到SQL Server数据库

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); 
    } 
} 

下面介绍如何创建WCF服务。

假设下进行: 比方说你有,你要发送到您,从你的问题出WinForm的客户端应用程序WCF服务tblExcel对象的列表。

第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步: 创建一个名为“ServiceContracts”下ExcelDataService项目的另一个文件夹,并创建一个新的接口,定义如下

[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,将项目类型设置为控制台应用程序。在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控制台主机管理器。

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

步骤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方法并传入参数。

希望这会有所帮助!

+0

谢谢+1 它TO0很难我,怎么我是新来的WCF,反正我会尽力...再次感谢 :d – Rooter

+0

我可以通过文件数据集的rslt作为参数传递给WCF方法 ? – Rooter

+0

是的,您可以将任何文件传递给WCF服务的字节数组(byte [])。我已经编写了一个服务,以字节[]取MS Word文档并处理它们,然后最终将它们保存到SQL数据库中。 –

这里有2个选项供您考虑。

private void button3_Click(object sender, EventArgs e) 
{ 
    System.Data.OleDb.OleDbConnection ExcelConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\Excel\\Desktop\\Coding\\DOT.NET\\Samples C#\\Export DataGridView to SQL Server Table\\Import_List.xls;Extended Properties=Excel 8.0;"); 

    ExcelConnection.Open(); 

    string expr = "SELECT * FROM [Sheet1$]"; 
    OleDbCommand objCmdSelect = new OleDbCommand(expr, ExcelConnection); 
    OleDbDataReader objDR = null; 
    SqlConnection SQLconn = new SqlConnection(); 
    string ConnString = "Data Source=Excel-PC;Initial Catalog=Northwind.MDF;Trusted_Connection=True;"; 
    SQLconn.ConnectionString = ConnString; 
    SQLconn.Open(); 

    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(SQLconn)) 
    { 

     bulkCopy.DestinationTableName = "tblTest"; 

     try 
     { 
      objDR = objCmdSelect.ExecuteReader(); 
      bulkCopy.WriteToServer(objDR); 
      ExcelConnection.Close(); 

      //objDR.Close() 
      SQLconn.Close(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.ToString()); 
     } 
    } 

} 

ALSO

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(); 
      } 
     } 
    } 

记住,你需要这些在顶部。

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; 
+0

谢谢,但有没有WCF连接 – Rooter