Silverlight 3文件对话框

时间:2011-04-27 14:42:17

标签: silverlight-3.0

好的 - 我有一个WCF服务,它从某个位置读取一个excel文件并将数据剥离到一个对象中。我需要的是能够允许我的程序的用户将Excel工作表上传到我的服务使用的文件位置。

Alternitivley我可以直接将Uploaded excel表传递给服务。

任何人都可以帮忙解决这个问题。我的服务代码是:

    public List<ImportFile> ImportExcelData(string FileName)
    {
        //string dataSource = Location + FileName;
        string dataSource = Location;
        string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dataSource.ToString() + ";Extended Properties=Excel 8.0;";
        var con = new OleDbConnection(conStr);
        con.Open();

        var data = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        var sheetName = data.Rows[0]["TABLE_NAME"].ToString();

        OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheetName + "] WHERE Status = '4'", con);
        OleDbDataAdapter oleda = new OleDbDataAdapter();
        oleda.SelectCommand = cmd;

        DataSet ds = new DataSet();
        oleda.Fill(ds, "Employees");
        DataTable dt = ds.Tables[0];

        var _impFiles = new List<ImportFile>();
        foreach (DataRow row in dt.Rows)
        {
            var _import = new ImportFile();

            _import.PurchaseOrder = row[4].ToString();

            try
            {
                var ord = row[8].ToString();
                DateTime dati = Convert.ToDateTime(ord);
                _import.ShipDate = dati;
            }
            catch (Exception)
            {
                _import.ShipDate = null;
            }


            ImportFile additionalData = new ImportFile();
            additionalData = GetAdditionalData(_import.PurchaseOrder);


            _import.NavOrderNo = additionalData.NavOrderNo;
            _import.IsInstall = additionalData.IsInstall;
            _import.SalesOrderId = additionalData.SalesOrderId;
            _import.ActivityID =  additionalData.ActivityID;
            _import.Subject =  additionalData.Subject ;

            _import.IsMatched = (_import.ShipDate != null & _import.NavOrderNo != "" & _import.NavOrderNo != null & _import.ShipDate > DateTime.Parse("01/01/1999") ? true : false);

            _import.UpdatedShipToField = false;
            _import.UpdatedShipToFieldFailed = false;
            _import.CreateNote = false;
            _import.CreateNoteFailed = false;
            _import.CompleteTask = false;
            _import.CompleteTaskFailed = false;
            _import.FullyCompleted = 0;
            _import.NotCompleted = false;
            _impFiles.Add(_import);

        }


        oleda.Dispose();
        con.Close();
        //File.Delete(dataSource);

        return _impFiles;

        } 

2 个答案:

答案 0 :(得分:0)

您需要修改您的服务以接受Stream而不是文件名,然后您可以将其保存到文件中(或直接从Stream解析,但我不会知道怎么做)。

然后在您的Silverlight应用中,您可以执行以下操作:

private void Button_Click(object sender, RoutedEventArgs ev)
{
    var dialog = new OpenFileDialog();
    dialog.Filter = "Excel Files (*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm|All Files (*.*)|*.*";
    if (dialog.ShowDialog() == true)
    {
        var fileStream = dialog.File.OpenRead();
        var proxy = new WcfService();
        proxy.ImportExcelDataCompleted += (s, e) =>
        {
             MessageBox.Show("Import Data is at e.Result");
             // don't forget to close the stream
             fileStream.Close();
        };
        proxy.ImportExcelDataAsync(fileStream);
    }
}

您也可以让您的WCF服务接受byte[]并执行类似的操作。

private void Button_Click(object sender, RoutedEventArgs ev)
{
    var dialog = new OpenFileDialog();
    dialog.Filter = "Excel Files (*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm|All Files (*.*)|*.*";
    if (dialog.ShowDialog() == true)
    {
        var length = dialog.File.Length;
        var fileContents = new byte[length];
        using (var fileStream = dialog.File.OpenRead())
        {
            if (length > Int32.MaxValue)
            {
                throw new Exception("Are you sure you want to load > 2GB into memory.  There may be better options");
            }
            fileStream.Read(fileContents, 0, (int)length);
        }
        var proxy = new WcfService();
        proxy.ImportExcelDataCompleted += (s, e) =>
                                                {
                                                    MessageBox.Show("Import Data is at e.Result");
                                                    // no need to close any streams this way
                                                };
        proxy.ImportExcelDataAsync(fileContents);
    }
}

更新

您的服务可能如下所示:

public List<ImportFile> ImportExcelData(Stream uploadedFile)
{
    var tempFile = HttpContext.Current.Server.MapPath("~/uploadedFiles/" + Path.GetRandomFileName());
    try
    {
        using (var tempStream = File.OpenWrite(tempFile))
        {
            uploadedFile.CopyTo(tempStream);
        }

        //string dataSource = Location + FileName;
        string dataSource = tempFile;
        string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dataSource.ToString() +
                        ";Extended Properties=Excel 8.0;";
        var con = new OleDbConnection(conStr);
        con.Open();
    }
    finally
    {
        if (File.Exists(tempFile))
            File.Delete(tempFile);
    }
}

答案 1 :(得分:0)

感谢Bendewey很棒。不得不稍微修改一下 - 我的服务:

        var tempFile = @"c:\temp\" + Path.GetRandomFileName();

        try  
        {        

            int length = 256;
            int bytesRead = 0;
            Byte[] buffer = new Byte[length];

            // write the required bytes
            using (FileStream fs = new FileStream(tempFile, FileMode.Create))
            {
                do
                {
                    bytesRead = uploadedFile.Read(buffer, 0, length);
                    fs.Write(buffer, 0, bytesRead);
                }
                while (bytesRead == length);
            }

            uploadedFile.Dispose();             



            string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dataSource.ToString() + ";Extended Properties=Excel 8.0;";
            var con = new OleDbConnection(conStr);

再次感谢您的帮助