C#excel隐藏和锁定行

时间:2017-12-13 17:22:35

标签: c# excel vba excel-vba

最近我一直在将项目从VBA转换为C#,但我遇到了一个问题:.Hidden(),. Locks()和.Protect()

在VBA实现中,如果我隐藏(行) - > gt; lock->保护,那么我不能取消隐藏行(按预期),但在C#实现中,如果我隐藏(行) - > lock->保护行可以取消隐藏(突出显示行,右键单击,取消隐藏)

是否有一些我缺少的东西,或者是否有一种不同的方式需要编写C#版本以产生与VBA版本相同的结果(行不能被取消隐藏)?

我已经将代码简化为这些重现结果的短片段。 两个版本都创建一个新工作簿,修改单元格,隐藏锁定保护行,以及保存/关闭工作簿。

C#版本:

using Excel = Microsoft.Office.Interop.Excel;
...

private void button1_Click(object sender, EventArgs e)
{

    Excel.Application ex = new Excel.Application();
    Excel.Workbooks Books = ex.Workbooks;


    //create and save the output workbook (so only .save() needs to be called later)
    Excel.Workbook OutputBook = Books.Add();
    OutputBook.SaveAs("C:\\TestingFolder\\Outputbook.xlsm", Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled);

    //write secret stuff
    OutputBook.Sheets[1].Cells[15,15] = "Stuff";

    //hide and lock rows around secret stuff
    OutputBook.Sheets[1].Range["10:20"].EntireRow.Hidden = true;
    OutputBook.Sheets[1].Range["10:20"].EntireRow.Locked = true;


    //protect the sheet with a bad password
    OutputBook.Sheets[1].Protect(
                                    "SomePassword123",//password
                                    false,  //drawing objects
                                    true,   //Contents
                                    false,  //scenarios
                                    false,  //user interface
                                    true,   //format cells
                                    true,   //format columns
                                    true,   //format rows
                                    false,  //insert columns
                                    false,  //insert rows
                                    true,   //insert hyperlinks
                                    false,  //delete columns
                                    false,  //delete rows
                                    true,   //allow sorting
                                    true,   //allow filtering
                                    true    //allow pivot tables
                                );


    //save and close output workbook
    OutputBook.Save();
    OutputBook.Close(false);


    //-----general cleanup start-----
    Books.Close();
    ex.Quit();

    System.Runtime.InteropServices.Marshal.ReleaseComObject(OutputBook);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(Books);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(ex);

    OutputBook = null;
    Books = null;
    ex = null;

    GC.Collect();
    //-----general cleanup end-----


    //show message that the task completed
    MessageBox.Show("done");

}

和VBA版本:

Private Sub CommandButton1_Click()

    'create and save the output workbook (so only .save() needs to be called later)
    Dim OutputBook As Workbook
    Set OutputBook = Workbooks.Add
    Call OutputBook.SaveAs("C:\TestingFolder\Outputbook.xlsm", ThisWorkbook.FileFormat)

    'write secret stuff
    OutputBook.Sheets(1).Cells(15, 15) = "Stuff"

    'hide and lock rows around secret stuff
    OutputBook.Sheets(1).Range("10:20").EntireRow.Hidden = True
    OutputBook.Sheets(1).Range("10:20").EntireRow.Locked = True

    'protect the sheet with a bad password
    OutputBook.Sheets(1).Protect Password:="SomePassword123", _
                                DrawingObjects:=False, _
                                Contents:=True, _
                                Scenarios:=False, _
                                AllowFormattingCells:=True, _
                                AllowInsertingHyperlinks:=True, _
                                AllowSorting:=True, _
                                AllowFiltering:=True, _
                                AllowUsingPivotTables:=True

    'save and close output workbook
    Call OutputBook.Save
    Call OutputBook.Close

    'show message that the task completed
    MsgBox "done"

End Sub

2 个答案:

答案 0 :(得分:0)

Protect方法中,格式行参数必须设置为false而不是true

答案 1 :(得分:0)

以下是保护和隐藏Excel工作表的代码。 使用下面所需的命名空间

using System;
using System.Data;
using Microsoft.CSharp;
using System.Collections;
using Excel=Microsoft.Office.Interop.Excel;

初始化Excel应用程序,Filepath是一个包含密码的字符串变量

string FilePath = @"C:\Filename.xlsx";
string Password = "12345";
Excel.Application ExcelApp = new Excel.Application();   // Initialize Excel Application
ExcelApp.DisplayAlerts = false;            
Excel.Workbook WB = ExcelApp.Workbooks.Open(FilePath);  // Initialize Excel Workbook

然后使用下面的代码隐藏工作表,此代码中的 toHide 是一个Arraylist,其中包含隐藏所需的工作表列表。

 foreach (Excel.Worksheet Worksheet in WB.Worksheets)
        {
        if (toHide.Contains(Worksheet.Name))
            {
                ((Excel.Worksheet)WB.Worksheets[Worksheet.Name]).Visible = Excel.XlSheetVisibility.xlSheetHidden;
            }
        }

为了保护工作表,这是代码; toProtect 这里是一个Arraylist,其中包含需要保护的工作表名称。

 ExcelApp.Visible = true;
        foreach (Excel.Worksheet Worksheet in WB.Worksheets)
        {
            if (toProtect.Contains(Worksheet.Name))
            {
                ((Excel.Worksheet)WB.Worksheets[Worksheet.Name]).Protect(Password);
            }
        }
        //WB.Save();
        ExcelApp.Visible = false;

如果有帮助,请告诉我。