C#将字符串拆分为Excel

本文关键字:Excel 拆分 字符串 | 更新日期: 2023-09-27 18:23:43

我一直在阅读Split字符串。我正在将数据从C#发送到Excel,其中一些文本可能相当长。因此,无需使用换行符或Excel自动填充。我希望数据在某个点中断并继续到它下面的行。这能实现吗?ProdDescription是此处的目标字段。这是我用来发送基本数据的代码:

        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;

C#将字符串拆分为Excel

这样试试:

        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来轻松地检查结果。。。