How to use AutoFit in C #?

1

I'm exporting data to an Excel spreadsheet and I'm not able to use AutoFit, could anyone 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;
}
    
asked by anonymous 27.01.2015 / 14:27

1 answer

1

You can use the AutoFit method in this way:

public void exportarExcel(InformacaoDB info, string nomeArquivo) {

    [...]

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

    [...]
}

One thing I think helps a lot, when you want to know how to do something, go to Excel itself and write a macro of what you intend to do, then just look at the code in Excel VBA and adapt.

    
27.01.2015 / 15:24