CamlCase
CamlCase

Reputation: 191

C# Split String to Excel

I have been reading up on Split string. I am sending data from C# to Excel and some of this text can be rather long. So without using word wrap or autofit with Excel. I would like the data to break at a certain point and continue to the row below it.Can this be accomplished? ProdDescription is the targeted field here. Here is the code I am using to send the basic data over :

        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;

Upvotes: 3

Views: 1501

Answers (1)

Gottfried Lesigang
Gottfried Lesigang

Reputation: 67311

Try it like this:

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

You could write the generated "lines" into an array or directly into your cells too. I just used Stringbuilder to check the result easily...

Upvotes: 1

Related Questions