Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freeze excel column with c#

Tags:

c#

excel

freeze

I generate an excel spread-cheat with c# and I want to freeze the first column. This is the code that I use :

    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???

like image 971
Mallouli Boulbeba Avatar asked Nov 05 '10 10:11

Mallouli Boulbeba


People also ask

What is the shortcut key to freeze multiple columns in Excel?

In the View tab, click the “freeze panes” drop-down under the “window” section. Select “freeze panes.” Alternatively, press the shortcut keys “Alt+W+F+F” one by one. The columns A B, C, D, and E are frozen as indicated by the grey line at the end of column E.

How do I freeze a specific area in Excel?

Select the cell in the upper-left corner of the range you want to remain scrollable. Select View tab, Windows Group, click Freeze Panes from the menu bar. Excel inserts two lines to indicate where the frozen panes begin.


2 Answers

The right solution is to add the following code :

        worksheet.Activate();
        worksheet.Application.ActiveWindow.SplitColumn = 1;
        worksheet.Application.ActiveWindow.FreezePanes = true;
like image 135
Mallouli Boulbeba Avatar answered Nov 13 '22 11:11

Mallouli Boulbeba


You need to set

yuorRange.Application.ActiveWindow.FreezePanes = true;

Have a look at

  • Window.FreezePanes Property
  • Window.SplitColumn Property
  • Window.SplitRow Property
like image 27
Adriaan Stander Avatar answered Nov 13 '22 11:11

Adriaan Stander