c# - 按长度拆分字符串到 Excel

标签 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++;
      }

最佳答案

您可以使用这种方法(警告未完全测试)

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

关于c# - 按长度拆分字符串到 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35246956/

相关文章:

c# - 如何在不打开浏览器的情况下在 C# 中运行 Web 进程

c# - 在 RavenDB 中指定集合名称

c# - 从excel中排序列表

.net - 用 VBA 实现无限及超越

c++ - 如何使用 "Microsoft Excel SDK 2013” 和 VS2015 社区构建 Excel 插件?

c# - 如果一个对象失败,EntityFramework 回滚所有事务

c# - 在 C# 中实现多个 IEnumerable

excel - 如何使用 Power Query 在同一列中进行增量求和?

c# - 与 winform 相比,来自控制台的过程

c# - 从数据表导出到 excel 时,如何阻止前导 0 被剥离?