2012-06-30 27 views
6

İlk ad, soyadı vb. Gibi temel bilgileri oluşturabileceğim bir wpf personel oluşturma penceresi var, bu REST web hizmetimde çalışanlar oluşturur. Bir örnek:Excel dokümanı içeriği için webservice

İstemci tarafı:

private void CreateStaffMember_Click(object sender, RoutedEventArgs e) 
    { 
     string uri = "http://localhost:8001/Service/Staff"; 
     StringBuilder sb = new StringBuilder(); 
     sb.Append("<Staff>"); 
     sb.AppendLine("<FirstName>" + this.textBox1.Text + "</FirstName>"); 
     sb.AppendLine("<LastName>" + this.textBox2.Text + "</LastName>"); 
     sb.AppendLine("<Password>" + this.passwordBox1.Password + "</Password>"); 
     sb.AppendLine("</Staff>"); 
     string NewStudent = sb.ToString(); 
     byte[] arr = Encoding.UTF8.GetBytes(NewStudent); 
     HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri); 
     req.Method = "POST"; 
     req.ContentType = "application/xml"; 
     req.ContentLength = arr.Length; 
     Stream reqStrm = req.GetRequestStream(); 
     reqStrm.Write(arr, 0, arr.Length); 
     reqStrm.Close(); 
     HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); 
     MessageBox.Show("Staff Creation: Status " + resp.StatusDescription); 
     reqStrm.Close(); 
     resp.Close(); 
    } 

Web Servis tarafı: bir excel elektronik tablosundan

#region POST 

    [OperationContract] 
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "/Staff")] 
    void AddStaff(Staff staff); 

    #endregion 

    public void AddStaff(Staff staff) 
    { 
     staff.StaffID = (++eCount).ToString(); 
     staff.Salt = GenerateSalt(); 
     byte[] passwordHash = Hash(staff.Password, staff.Salt); 
     staff.Password = Convert.ToBase64String(passwordHash); 
     staffmembers.Add(staff); 
    } 

Bütün o tarafta ince, ama Im seyir için "ithal" personel bilgilerini değil içe aktarım doğru sözcükse, ancak böyle bir e-tabloda yer alan ad ve soyadlarını almak ve bunları istemci tarafındaki wpf uygulamasından web hizmetine eklemek istiyorum.

Nasıl yapmalıyım? Benim açık dosya iletişim vardır:

private void Import_Click(object sender, RoutedEventArgs e) 
    { 
     Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); 

     // Show open file dialog box 
     Nullable<bool> result = dlg.ShowDialog(); 

     // Process open file dialog box results 
     if (result == true) 
     { 
      // Open document 
      string filename = dlg.FileName; 
     } 
    } 

Yani o zaman iç içeriğini alıp web hizmeti göndermeden hakkında gitmek benim excel elektronik tabloya açmak? Gerçekten kod üzerinde sıkışmış veya bu konuda gitmek için:/

Sadece adlarını elle yazmak yerine personel ekleyerek otomatik bir yol arıyor, ama personel excel doc olarak görmek açık dosya istedim bir şey seçilebilir iletişim kutusu. İçteki yapı her zaman aynı adı ve soyadı olacaktır. ilk isim, kolon 'B' soyadı ve sütun ise 'A' 'C' olan enter image description here

(Sütun:

+0

bu, hiçbir şekilde sorunuza cevap vermez ... ancak verileri bir DB'de depolamak daha kolay olmaz mı? – Pynner

cevap

4

Öncelikle burada aktarmak istediğiniz Personel içeren benim test Excel dosyası olduğunu şifre ...)

Tamam, bu nedenle kodu, web servis işleri çağırarak varsayarak, işte Import_Click yönteminin sürümü (ve yeni personel kaydetmek için genel bir yöntem) 'dir:

private void Import_Click(object sender, RoutedEventArgs e) 
    { 
     Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); 

     // Show open file dialog box 
     Nullable<bool> result = dlg.ShowDialog(); 

     // Process open file dialog box results 
     if (result == true) 
     { 
      // Open document 
      string filename = dlg.FileName; 

      Microsoft.Office.Interop.Excel.Application vExcelObj = new Microsoft.Office.Interop.Excel.Application(); 
      try 
      { 
       Workbook theWorkbook = vExcelObj.Workbooks.Open(filename, Type.Missing, true); 

       Worksheet sheet = theWorkbook.Worksheets[1]; // This is assuming that the list of staff is in the first worksheet 

       string vFirstName = "temp"; 
       string vLastName = "temp"; 
       string vPassword = "temp"; 
       int vIndex = 1; 

       while (vFirstName != "") 
       { 
        // Change the letters of the appropriate columns here! 
        // In my example, 'A' is first name, 'B' is last name and 'C' is the password 
        vFirstName = sheet.get_Range("A" + vIndex.ToString()).Value.ToString(); 
        vLastName = sheet.get_Range("B" + vIndex.ToString()).Value.ToString(); 
        vPassword = sheet.get_Range("C" + vIndex.ToString()).Value.ToString(); 

        this.SaveNewStaff(vFirstName, vLastName, vPassword); 

        vIndex++; 

       } 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("Error processing excel file : " + ex.Message); 
      } 
      finally { 
       vExcelObj.Quit(); 
      } 
     } 
    } 

    private void SaveNewStaff(string firstName, string lastName, string password) { 
     string uri = "http://localhost:8001/Service/Staff"; 
     StringBuilder sb = new StringBuilder(); 
     sb.Append("<Staff>"); 
     sb.AppendLine("<FirstName>" + firstName + "</FirstName>"); 
     sb.AppendLine("<LastName>" + lastName + "</LastName>"); 
     sb.AppendLine("<Password>" + password + "</Password>"); 
     sb.AppendLine("</Staff>"); 
     string NewStudent = sb.ToString(); 
     byte[] arr = Encoding.UTF8.GetBytes(NewStudent); 
     HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri); 
     req.Method = "POST"; 
     req.ContentType = "application/xml"; 
     req.ContentLength = arr.Length; 
     Stream reqStrm = req.GetRequestStream(); 
     reqStrm.Write(arr, 0, arr.Length); 
     reqStrm.Close(); 
     HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); 
     //MessageBox.Show("Staff Creation: Status " + resp.StatusDescription); 
     reqStrm.Close(); 
     resp.Close(); 
    } 

Not: MessageBox'ı c Eğer liste uzunsa, onun tarafından rahatsız edilmediğinden emin olmak için tüm web hizmetine, ancak her personel yaratımı için onay gerekiyorsa "unREM" ücretsiz. Aynı öğretimde, yaratımın başarılı bir şekilde gerçekleştiği yönünde bir doğrulama yoktur. İyi bir doğrulama süreci oluşturmak için daha fazla bilgiye ihtiyacım var. Ayrıca ÇOK önemli, kaydettiğiniz personel zaten listede var olup olmadığını doğrulamaz. Bu içe aktarma yordamını birkaç kez yeniden çalıştırırsanız, yinelenen girişler oluşturabilir (ve büyük olasılıkla).

Alkış

+1

vay gerçekten çok güzel! Sorduğum her şeyi anladın ve lütufla güzelce cevap verdi! +1 millet! –

+1

LOL Benim için zevk. Ayrıca, küçük bir bellek (veya kaynak yönetimi) sorunu olduğunu fark ettim. Büyük bir anlaşma değil, ancak bu prosedürü birden çok kez çalıştırıyorsanız, geriye kalan "EXCEL.EXE" süreçlerini öldürmek isteyebilirsiniz. Sadece fark ettim. – JFTxJ

+2

Ayrıca, kodumun, "ilk ad" sütununda hiç metin içermeyen excel dosyasındaki ilk satırda duracağını unutmayın. – JFTxJ