How to do a text break in Excel programmatically with a C check #

Asked

Viewed 1,673 times

13

I am using the Microsoft.Office.Interop.Excel to create an Excel report from a txt file.

Everything works perfect, but sometimes some columns become extremely large and when we need to print, it is necessary to resize and it gets awful

When I try to break it using the Range.Style.WrapText = true, it gets weird, like:

Minha maneira

I’m thinking of a way to break phrases that have more than 20 characters. and get something like that:

A maneira que meu chefe quer

the worst is that in excel, when I click on the text (as I should do when I edit it) it gets the way I wanted it to.

inserir a descrição da imagem aqui

here my code.

    //ignorem o loop, ele é para pegar o texto exato vindo do txt
    for (int x = 0; x < text.Length - 2; x++)
    {
            if(text[x].Length > 20)
            {
                //fazer a quebra...mas como?
                app.Cells[i,j] =  text[x + 1].Trim();
            }
            else
            {
                app.Cells[i,j] =  text[x + 1].Trim();
            }
    }
    //Range usado para a formatação.
    Range formatPaiP1 = app.get_Range(letraColunaP1, BuscarAlfabeto(9) + (i).ToString());
    formatPaiP1.WrapText = true;
    formatPaiP1.EntireRow.AutoFit();
    formatPaiP1.VerticalAlignment = Constants.xlCenter;
    formatPaiP1.EntireColumn.AutoFit();
    formatPaiP1.Font.Bold = true;
    formatPaiP1.Font.Name = "Arial";
    formatPaiP1.Font.Size = 12;
  • The thing is to go with Range.Style.WrapText = true really. It’s "weird" because it occupied the space of 3 lines instead of two? Resize the column Oras. Leave wider to occupy only two lines.

  • The columns are also with formatPaiP1.EntireColumn.AutoFit();

  • In Excel to use line break you have to press Alt + Enter, have you tried to put these two characters at the end of the text? I did not put as an answer because I do not have Visual Studio here to test, if it works out let me know I create as an answer!

  • @Guilhermegolfetto already tried to change the format of the txt file to csv?

  • @Guilhermegolfetto Already tried to add " r n" to the string?

1 answer

6


I solved the problem with the help of @rodorgas in an "alternative" way (read:technical adequacy). I made the following change:

formatPaiP1.WrapText = true;
formatPaiP1.EntireRow.RowHeight = 33;

I noticed that when using Wraptext the line was 66 height, breaking it in half, excel adjusts it correctly in all my cases.

This is a solution that worked exclusively for my project. I imagine you have the same problem maybe you can not adopt the same "logic".

Upshot:

Resultado

Thank you all for your help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.