【问题标题】:How do I auto size columns through the Excel interop objects?如何通过 Excel 互操作对象自动调整列大小?
【发布时间】:2010-05-21 17:53:56
【问题描述】:

下面是我用来将数据加载到 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();
        }
    }
}

【问题讨论】:

    标签: c# excel-2003 excel-interop


    【解决方案1】:

    在你的 TODO 点添加这个:

    aRange.Columns.AutoFit();

    【讨论】:

    • 还有一个aRange.Rows.AutoFit()
    • 使用@nawfal 答案:aRange.EntireColumn.AutoFit();
    • 以防万一您不知道:AutoFit() 不会将列置于自动调整以适应您稍后添加的内容的模式,而是仅适用于当前数据。所以Range必须在调用AutoFit()之前完全填充。
    • 这是另一个好方法:workSheet.UsedRange.Columns.AutoFit();
    【解决方案2】:

    这可能为时已晚,但如果你添加

     worksheet.Columns.AutoFit();
    

     worksheet.Rows.AutoFit();
    

    它也有效。

    【讨论】:

    • 我更喜欢这个。如果您不关心需要调整大小的特定列并且只想自动调整整个工作表,这将更加有用。
    【解决方案3】:

    还有

    aRange.EntireColumn.AutoFit();
    

    What is the difference between Range.Columns and Range.EntireColumn

    【讨论】:

      【解决方案4】:

      此方法打开已创建的 excel 文件,根据 第 3 行自动调整所有工作表的所有列。如您所见,范围在 excel 中选择了 From "A3 to 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);
              }
          }
      

      【讨论】:

        【解决方案5】:

        看看这篇文章,它与您的问题不完全匹配,但适合它:

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-09-15
          • 2023-03-26
          • 1970-01-01
          • 2018-08-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-08-14
          相关资源
          最近更新 更多