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

我试图用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); } } 

这里是如何创build一个WCF服务。

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

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

 [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项目下创build另一个名为“ ServiceContracts ”的文件夹,并创build一个具有以下定义的新界面

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

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

 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解决scheme中添加一个新项目并将其命名为ExcelDataServiceConsoleHostManager ,将项目types设置为控制台应用程序。 在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文件中添加以下configuration:

 <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> 

确保所有参考都添加到项目中。 一旦构build成功,按F5键启动Excel数据服务控制台主机pipe理器。

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

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

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

步骤7:将app.config文件添加到客户端(如果尚未添加)并粘贴以下configuration

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

保存所有文件并parsing任何引用(WCF使用System.ServiceModel.dll)。

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

我会把来自客户端的调用包装到一个try-catch块中以捕获任何exception。

编辑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方法并传递参数。

希望这可以帮助!

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

 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;