如何将Excel文件从WinForms客户端传递到WCF服务以及SQL Server表中? [英] How to pass an Excel file from a WinForms client to a WCF service and into an SQL Server table?
问题描述
如何将Excel文件从WinForms客户端传递到WCF服务并传递到SQL Server表中?
How to pass an Excel file from a WinForms client to a WCF service and into an SQL Server table?
任何人都可以提供任何指导,代码或建议吗?
Can anyone provide any guidance, code, or advice?
- 将Excel文件作为参数的WCF服务合同和实现
- 合同实施应将该Excel文件插入SQL Server的varbinary(MAX)列中.
推荐答案
我相信那里的专家可以对此进行改进,但这是基础知识...
I'm sure the experts out there can improve upon this, but here are the basics ...
在服务器上
1a.将新的OperationContract添加到您的界面(例如IService.cs)
1a. Add a new OperationContract to your Interface (eg. IService.cs)
[OperationContract]
string UploadBinaryFile(byte[] aByteArray);
1b.在合同实现(例如Service.cs)中插入SQL Server表中
1b. Insert into SQL Server table, in your contract Implementation (eg. Service.cs)
public string UploadBinaryFile(byte[] aByteArray)
{
try
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = MyConnectionString; // from saved connection string
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO MyTestTable(BinaryFile) VALUES (@binaryfile)", conn))
{
cmd.Parameters.Add("@binaryfile", SqlDbType.VarBinary, -1).Value = aByteArray;
cmd.ExecuteNonQuery();
}
return "1"; // to me, this indicates success
}
catch (Exception ex)
{
return "0: " + ex.Message; // return an error indicator + ex.message
}
}
在客户端上
2a.使用OpenFileDialog组件,通过大多数Windows应用程序使用的标准对话框浏览文件系统中的文件.
2a. Use the OpenFileDialog component to browse for files on your filesystem using the standard dialogue box that's used by most Windows applications.
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
txtUploadFilePath.Text = openFileDialog1.FileName;
}
2b.将文件内容加载到字节数组中
2b. Load the file's contents into a byte array
var byte[] BinaryFile = System.IO.File.ReadAllBytes(txtUploadFilePath.Text);
2c.调用WCF合约,传入字节数组
2c. Call your WCF contract, passing in the byte array
string UploadResponse = client.UploadBinaryFile(BinaryFile);
正在工作...是的:-)
It's working... YAY :-)
这篇关于如何将Excel文件从WinForms客户端传递到WCF服务以及SQL Server表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!