How to use Autofit in C#?

Asked

Viewed 296 times

1

I am exporting data to an Excel spreadsheet and am unable to use Autofit, someone could help me?

Code:

public void exportarExcel(InformacaoDB info, string nomeArquivo)
{
    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
    Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
    Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;

    object misValue = System.Reflection.Missing.Value;
    xlWorkBook = xlApp.Workbooks.Add(misValue);

    xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

    xlWorkSheet.Cells[1, 1] = "Cliente";
    xlWorkSheet.Cells[1, 2] = "Nome do Servidor";
    xlWorkSheet.Cells[1, 3] = "Uso de Processamento (%)";
    xlWorkSheet.Cells[1, 4] = "Uso de Armazenamento (%)";

    xlWorkSheet.Cells[2, 1] = info.Cliente;
    xlWorkSheet.Cells[2, 2] = info.NomeServidor;
    xlWorkSheet.Cells[2, 3] = info.UsoProcessamento;
    xlWorkSheet.Cells[2, 4] = info.UsoArmazenamento;
}
  • C# has no AutoFit. It is likely that the used API has, but there is nothing in your code that indicates this. Can you give more information? I found this: https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.range.autofit.aspx

  • I wanted to format Excel cells by code C#, type Alignment, width and auto height, those things.

  • @Thiagobeltrame I believe you can solve the problem the way I posted in the answer

1 answer

1

You can use the method AutoFit in that way:

public void exportarExcel(InformacaoDB info, string nomeArquivo) {

    [...]

    xlWorkSheet.get_Range("A:D").EntireColumn.AutoFit();

    [...]
}

Something that I think helps a lot, when you want to know how to do something, go to Excel itself and record a macro of what you want to do, then just see the code in Excel VBA and adapt.

Browser other questions tagged

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