【问题标题】:Insert data into SQL Server database from an Excel file从 Excel 文件将数据插入 SQL Server 数据库
【发布时间】:2017-04-08 14:12:32
【问题描述】:

我正在尝试使用 excel 文件将数据插入数据库。这段代码对我来说很好。但我将它与 Windows 窗体应用程序一起使用。如何将此代码更改为 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);
    }
}

【问题讨论】:

    标签: c# sql-server excel wcf


    【解决方案1】:

    这是创建 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,将项目类型设置为控制台应用程序。在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 数据服务控制台主机管理器。

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

    第 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 这对我来说很难,因为我是 wcf 的新手,无论如何我会尝试......再次感谢:D
    • 我可以将文件 DataSet rslt 作为参数传递给 WCF 方法吗?
    • 是的,您可以将字节数组 (byte[] ) 中的任何文件传递给 WCF 服务。我编写了一个服务,它以 byte[] 格式获取 MS Word 文档并对其进行处理,然后最终将它们保存到 SQL 数据库中。
    • 我如何在其中使用 byte[] 数组,你能在这里提供我的示例吗,plz :(
    • 在显示支持文件传输的答案中添加了 Edit 2。
    【解决方案2】:

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

    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;
    

    【讨论】:

    • 谢谢,但没有 WCF 连接
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多