首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何通过Excel互操作对象自动调整列的大小?

如何通过Excel互操作对象自动调整列的大小?
EN

Stack Overflow用户
提问于 2010-05-22 01:53:56
回答 3查看 127.5K关注 0票数 70

下面是我用来将数据加载到Excel工作表中的代码,但我希望在加载数据后自动调整列的大小。有人知道自动调整列大小的最佳方法吗?

代码语言:javascript
复制
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();
        }
    }
}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2884356

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档