nor*_*ndo 62 c# excel-2003 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();
        }
    }
}
Igb*_*man 105
在您的TODO点添加:
aRange.Columns.AutoFit();
小智 34
这可能为时已晚,但如果你添加
 worksheet.Columns.AutoFit();
要么
 worksheet.Rows.AutoFit();
它也有效.
naw*_*fal 27
还有
aRange.EntireColumn.AutoFit();
请参阅Range.Columns和Range.EntireColumn之间的区别.