簡體   English   中英

按長度將字符串拆分為Excel

[英]Split string by length to 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++;
      }

您可以使用這種方法(警告尚未完全測試)

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();
}

這是一個似乎可行的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM