将string按长度拆分为Excel

我目前正在发送和分割长长的数据到Excel。 每个分割打印在一个新的行中。 我想将现有数据中的pipe道符号拆分为字符长度为85的分裂,但是在字符85处有可能将字符分成两半。 如果要分割实际的单词,我将如何告诉它进一步分解数据。 我知道如果在85时,也应该find一个空格。 我很好奇添加什么。

// 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++; } 

你可以使用这种方法(警告没有完全testing)

 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版本。 正如我的评论所build议的那样,它将空格分隔string,然后testing添加一个单词是否使当前行的长度大于最大值(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