在 C# 中冻结 Excel 列

7

我使用C#生成一个Excel电子表格,我想要冻结第一列。

这是我所使用的代码:

    public static void SaveToExcel(object[,] data)
    {
        Excel = Microsoft.VisualBasic.Interaction.CreateObject("Excel.Application", String.Empty);
        Excel.ScreenUpdating = false;
        dynamic workbook = Excel.workbooks;
        workbook.Add();

        dynamic worksheet = Excel.ActiveSheet;

        const int left = 1;
        const int top = 1;
        int height = data.GetLength(0);
        int width = data.GetLength(1);
        int bottom = top + height - 1;
        int right = left + width - 1;

        if (height == 0 || width == 0)
            return;

        dynamic rg = worksheet.Range[worksheet.Cells[top, left], worksheet.Cells[bottom, right]];
        rg.Value = data;

        // Set borders
        for (var i = 1; i <= 4; i++)
            rg.Borders[i].LineStyle = 1;

        // Set header view
        dynamic rgHeader = worksheet.Range[worksheet.Cells[top, left], worksheet.Cells[top, right]];
        rgHeader.Font.Bold = true;
        rgHeader.Interior.Color = 189 * (int)Math.Pow(16, 4) + 129 * (int)Math.Pow(16, 2) + 78;
        rg.EntireColumn.AutoFit();

        // Show excel app
        Excel.ScreenUpdating = true;
        Excel.Visible = true;
    }

Could You Please Help me???

2个回答

15

正确的解决方案是添加以下代码:

        worksheet.Activate();
        worksheet.Application.ActiveWindow.SplitColumn = 1;
        worksheet.Application.ActiveWindow.FreezePanes = true;

2

谢谢你的回答,虽然它没有解决我的问题,但是它对我非常有帮助。 - Mallouli Boulbeba

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接