按字符串将字符串拆分为Excel

时间:2016-02-06 21:58:05

标签: c# excel

我目前正在向Excel发送和分割长行数据。每个分割都打印在一个新行中。我想改变这一点,从在现有数据中的管道符号处拆分到以85的字符长度进行拆分,但是,有可能在字符85处它可以将一个单词拆分为两个。如果要分割实际单词,我怎么能告诉它进一步拆分成数据。我知道如果在85后它也应该找到一个空格。我很想知道要添加什么。

// Add Description
      string DescriptionSplit = srcAddOnPanel.Controls["txtProductDescAddOn" + AddRow].Text;
      string[] descriptionParts = DescriptionSplit.Split('|');
      int i;
      for (i = 0; i <= descriptionParts.GetUpperBound(0); i++)
      {
          worksheet.Rows[currentRow].Insert();    //applies the description for the default bundle row
          worksheet.Rows[currentRow].Font.Bold = false;
          worksheet.Cells[currentRow, "E"].Value = rowIndent + descriptionParts[i].Trim();
          currentRow++;
      }

2 个答案:

答案 0 :(得分:0)

您可以使用此方法(警告未经过全面测试)

int x = 85;
int y = 0;
int currentRow = 0;

// Loop until you have at least 85 char to grab
while (x + y < DescriptionSplit.Length)
{
    // Find the first white space after the 85th char
    while (x + y < DescriptionSplit.Length && 
          !char.IsWhiteSpace(DescriptionSplit[x+y]))
        x++;
    // Grab the substring and pass it to Excel for the currentRow
    InsertRowToExcel(DescriptionSplit.Substring(y, x), currentRow);

    // Prepare variables for the next loop
    currentRow++;
    y = y + x + 1;
    x = 85;
}
// Do not forget the last block
if(y < DescriptionSplit.Length)
    InsertRowToExcel(DescriptionSplit.Substring(y), currentRow);
...

void InsertRowToExcel(string toInsert, int currentRow)
{
      worksheet.Rows[currentRow].Insert();    
      worksheet.Rows[currentRow].Font.Bold = false;
      worksheet.Cells[currentRow, "E"].Value = rowIndent + toInsert.Trim();
}

答案 1 :(得分:0)

这是一个似乎有用的VBA版本。正如我在评论中所建议的那样,它用空格分隔字符串,然后测试添加一个单词是否使当前行的长度大于最大值(85)。正如通常情况下这些事情的最后一句话正确填充是很难的。

如果这适合你,它应该很简单,可以修改为C#。如果不是这样,请告诉我:

Sub ParseRows()
Const ROW_LENGTH As Long = 85
Dim Text As String
Dim Words As Variant
Dim RowContent As String
Dim RowNum As Long
Dim i As Long

Text = ActiveCell.Text
Words = Split(Text, " ")
RowNum = 2

For i = LBound(Words) To UBound(Words)
    If Len(RowContent & Words(i) & " ") > ROW_LENGTH Then
        ActiveSheet.Range("A" & RowNum).Value = RowContent
        RowNum = RowNum + 1
        If i = UBound(Words) Then
            RowContent = Words(i)
        Else
            RowContent = ""
        End If
    Else
        RowContent = RowContent & Words(i) & " "
    End If
Next i
If RowContent <> "" Then ActiveSheet.Range("A" & RowNum).Value = RowContent
End Sub