web-dev-qa-db-fra.com

Comment dimensionner automatiquement les colonnes via les objets d'interopérabilité Excel?

Vous trouverez ci-dessous le code que j'utilise pour charger les données dans une feuille de calcul Excel, mais je cherche à redimensionner automatiquement la colonne une fois les données chargées. Est-ce que quelqu'un connaît le meilleur moyen de dimensionner automatiquement les colonnes?

using Microsoft.Office.Interop;

public class ExportReport
{
    public void Export()
    {
        Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
        Excel.Workbook wb;
        Excel.Worksheet ws;
        Excel.Range aRange;
        object m = Type.Missing;
        string[,] data;
        string errorMessage = string.Empty;
        try
        {
            if (excelApp == null)
                throw new Exception("Excel could not be started.");

            // Create the workbook and worksheet.
            wb = excelApp.Workbooks.Add(Office.Excel.XlWBATemplate.xlWBATWorksheet);
            ws = (Office.Excel.Worksheet)wb.Worksheets[1];

            if (ws == null)
                throw new Exception("Could not create worksheet.");

            // Set the range to fill.
            aRange = ws.get_Range("A1", "E100");

            if (aRange == null)
                throw new Exception("Could not get a range.");

            // Load the column headers.
            data = new string[100, 5];
            data[0, 0] = "Column 1";
            data[0, 1] = "Column 2";
            data[0, 2] = "Column 3";
            data[0, 3] = "Column 4";
            data[0, 4] = "Column 5";

            // Load the data.
            for (int row = 1; row < 100; row++)
            {
                for (int col = 0; col < 5; col++)
                {
                    data[row, col] = "STUFF";
                }
            }

            // Save all data to the worksheet.
            aRange.set_Value(m, data);
            // Atuo size columns
            // TODO: Add Code to auto size columns.

            // Save the file.
            wb.SaveAs("C:\Test.xls", Office.Excel.XlFileFormat.xlExcel8, m, m, m, m, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, m, m, m, m, m);
            // Close the file.
            wb.Close(false, false, m);
        }
        catch (Exception) { }
        finally
        {
            // Close the connection.
            cmd.Close();
            // Close Excel.
            excelApp.Quit();
        }
    }
}
61
norlando

Ajoutez ceci à votre point TODO:

aRange.Columns.AutoFit();

101
Igby Largeman

Cela pourrait être trop tard, mais si vous ajoutez

 worksheet.Columns.AutoFit();

ou

 worksheet.Rows.AutoFit();

ça marche aussi.

32
Matheus Shita

Il y a aussi

aRange.EntireColumn.AutoFit();

Voir Quelle est la différence entre Range.Columns et Range.EntireColumn .

26
nawfal

Jetez un coup d'œil à cet article, il ne correspond pas exactement à votre problème, mais convient:

2
Kyle Rozendo

Cette méthode ouvre le fichier Excel déjà créé. Ajustez automatiquement toutes les colonnes de toutes les feuilles en fonction de ème ligne. Comme vous pouvez le voir, la plage est sélectionnée à partir de "A3 à K3" dans Excel.

 public static void AutoFitExcelSheets()
    {
        Microsoft.Office.Interop.Excel.Application _Excel = null;
        Microsoft.Office.Interop.Excel.Workbook excelWorkbook = null;
        try
        {
            string ExcelPath = ApplicationData.PATH_Excel_FILE;
            _Excel = new Microsoft.Office.Interop.Excel.Application();
            _Excel.Visible = false;
            object readOnly = false;
            object isVisible = true;
            object missing = System.Reflection.Missing.Value;

            excelWorkbook = _Excel.Workbooks.Open(ExcelPath,
                   0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
                   true, false, 0, true, false, false);
            Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;
            foreach (Microsoft.Office.Interop.Excel.Worksheet currentSheet in excelSheets)
            {
                string Name = currentSheet.Name;
                Microsoft.Office.Interop.Excel.Worksheet excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item(Name);
                Microsoft.Office.Interop.Excel.Range excelCells =
(Microsoft.Office.Interop.Excel.Range)excelWorksheet.get_Range("A3", "K3");
                excelCells.Columns.AutoFit();
            }
        }
        catch (Exception ex)
        {
            ProjectLog.AddError("Excel ERROR: Can not AutoFit: " + ex.Message);
        }
        finally
        {
            excelWorkbook.Close(true, Type.Missing, Type.Missing);
            GC.Collect();
            GC.WaitForPendingFinalizers();
            releaseObject(excelWorkbook);
            releaseObject(_Excel);
        }
    }
2
Charlie