Development Tip

Excel interop 개체를 통해 열 크기를 자동으로 조정하려면 어떻게합니까?

yourdevel 2020. 11. 29. 12:20
반응형

Excel interop 개체를 통해 열 크기를 자동으로 조정하려면 어떻게합니까?


다음은 데이터를 Excel 워크 시트에로드하는 데 사용하는 코드이지만 데이터가로드 된 후 열 크기를 자동으로 조정하려고합니다. 열 크기를 자동으로 조정하는 가장 좋은 방법을 아는 사람이 있습니까?

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

TODO 지점에 다음을 추가하십시오.

aRange.Columns.AutoFit();


너무 늦을 수 있지만 추가하면

 worksheet.Columns.AutoFit();

또는

 worksheet.Rows.AutoFit();

그것은 또한 작동합니다.


또한

aRange.EntireColumn.AutoFit();

Range.Columns 및 Range.EntireColumn의 차이점무엇입니까?를 참조하십시오 .


이 기사를 살펴보십시오. 문제와 정확히 일치하지는 않지만 적합합니다.


이 방법은 이미 생성 된 Excel 파일을 열고 3rd Row를 기준으로 모든 시트의 모든 열을 자동 맞춤합니다 . 보시다시피 범위는 Excel 에서 "A3 ~ K3" 에서 선택 됩니다.

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

참고URL : https://stackoverflow.com/questions/2884356/how-do-i-auto-size-columns-through-the-excel-interop-objects

반응형