如何使用c#中的openxml为excel中的某些指定单元格和工作表启用只读权限

时间:2016-10-06 12:38:28

标签: c# excel openxml

我正在阅读XML数据,然后我粘贴到数据集,我创建了电子表格并将数据复制到电子表格中的工作表。现在我想只允许一些工作表和单元格为只读。为了防止在某些工作表中没有更改标题和数据,所以我发布了用于使用开放XML将XML转换为excel的代码。所以我需要防止写一些纸张,也要防止一些纸张。 enter code here

 public void ExportDSToExcel(DataSet ds, string dest)
{
    using (var workbook = SpreadsheetDocument.Create(dest, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
    {
        var workbookPart = workbook.AddWorkbookPart();
        workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
        workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();

        uint sheetId = 1;

        foreach (DataTable table in ds.Tables)
        {
            var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
            var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
            sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);                

            DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
            string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);

            if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)
            {
                sheetId =
                    sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;
            }

            DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = table.TableName };
            sheets.Append(sheet);

            DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();

            List<String> columns = new List<string>();
            foreach (DataColumn column in table.Columns)
            {
                columns.Add(column.ColumnName);

                DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
                headerRow.AppendChild(cell);
            }

            sheetData.AppendChild(headerRow);

            foreach (DataRow dsrow in table.Rows)
            {
                DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
                foreach (String col in columns)
                {
                    DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                    cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                    cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
                    newRow.AppendChild(cell);
                }

                sheetData.AppendChild(newRow);
            }
        }
    }
}
    protected void Button1_Click(object sender, EventArgs e)
    {
        if(txtname.Text != null)
        {
            if (FileUpload1.HasFile == true)
            {
        string myXMLfile = "/uploads/" + FileUpload1.FileName;
        FileUpload1.SaveAs(Server.MapPath(myXMLfile));
        string dest = "D:/uploads/" + txtname.Text+".xlsx";
        DataSet ds = new DataSet();
        try
        {

            ds.ReadXml(myXMLfile);

        }
        catch (Exception ex)
        {
            lblstatus.Text=(ex.ToString());
        }
            ExportDSToExcel(ds, dest);

    }
            else
            {
               lblstatus.Text = "Please Upload the file ";
            }
        }
        else {

            lblstatus.Text = "Please enter the name ";
        }

    }
}

提前致谢,请帮助我在此代码中找到解决方案。

1 个答案:

答案 0 :(得分:0)

我们可以通过密码以不同的方式自定义保护。将excel表格指定的区域或列或行作为只读或整页表格通过密码保护表格。如果我们要保护整张表使用这个代码

 PageMargins pageM = sheetPart.Worksheet.GetFirstChild<PageMargins>();
                   SheetProtection sheetProtection = new SheetProtection();
                   sheetProtection.Password = "admin";
                   sheetProtection.Sheet = true;
                   sheetProtection.Objects = true;
                   sheetProtection.Scenarios = true;
                   ProtectedRanges pRanges = new ProtectedRanges();
                   ProtectedRange pRange = new ProtectedRange();
                   ListValue<StringValue> lValue = new ListValue<StringValue>();
                   lValue.InnerText = ""; //set cell which you want to make it editable
                   pRange.SequenceOfReferences = lValue;
                   pRange.Name = "not allow editing";
                   pRanges.Append(pRange);
                   sheetPart.Worksheet.InsertBefore(sheetProtection, pageM);
                   sheetPart.Worksheet.InsertBefore(pRanges, pageM);

如果我们希望指定的页面只读,那么首先按名称给出一个条件过滤器然后给出这段代码。在这段代码中lValue.InnerText =“”;因为我们没有提到细胞有权克服这种保护。如果我们提到单元格,我们可以编辑到该限制。