2015-11-21 157 views
3

我一直在閱讀拆分字符串。我正在將數據從C#發送到Excel,並且其中一些文本可能會很長。因此,不要使用Word換行或使用Excel自動調整。我希望數據能夠在某個點上突破並繼續到它下面的行。可以完成這項工作嗎? ProdDescription是這裏的目標領域。下面是我用來送過來的基本數據的代碼:C#將字符串拆分爲Excel

 worksheet.Cells[3, "E"].Value = txtCustomer.Text; 
     worksheet.Cells[4, "E"].Value = txtDate.Text; 
     worksheet.Cells[5, "E"].Value = cboTerms.Text; 
     worksheet.Cells[6, "E"].Value = txtProposalID.Text; 
     worksheet.Cells[10, "D"].value = frmProposal.QtyMaintxt.Text; 
     worksheet.Cells[10, "E"].value = frmProposal.ProdName.Text; 
     worksheet.Cells[11, "E"].value = frmProposal.ProdDescription.Text;** 
     worksheet.Cells[10, "F"].value = frmProposal.ListPrice.Text; 
     worksheet.Cells[10, "G"].value = frmProposal.MaxDiscount.Text; 
+1

AFAIK,BCL中沒有這樣的方法,開箱即用。你是否想要插入換行符,但將文本保留在Excel中的單個單元格中,或者希望被包裝的行向下佔用相鄰的單元格?無論哪種情況,即使您計劃在Excel中使用固定寬度的字體,預測您需要分割線條的右邊距也是相當棘手的。 –

回答

1

試試這樣說:

 string s = "This is a rather long text. This is a rather long text. This is a rather long text. This is a rather long text. This is a rather long text. This is a rather long text. "; 
     s += "This is a rather long text. This is a rather long text. This is a rather long text. This is a rather long text. This is a rather long text. This is a rather long text. "; 
     s += "This is a rather long text. This is a rather long text. This is a rather long text. This is a rather long text. This is a rather long text. This is a rather long text. "; 

     var words = s.Split(new char[] { ' ' }); 

     int maxLineCount = 35; 
     var sb=new System.Text.StringBuilder(); 

     string part=words[0]; 
     int i=1; 
     while (true) { 
      if (i >= words.Length) 
       break; 
      if ((part + " " + words[i]).Length < maxLineCount) 
       part += " " + words[i]; 
      else { 
       sb.AppendLine(part); 
       part = words[i]; 
      } 
      i++; 
     } 
     var result = sb.ToString(); 

你可以寫生成的「線」到一個數組或直接進入你的細胞過。我只是用Stringbuilder輕鬆檢查結果...