问题
I have created one Sheet, which i could protect using OpenXml code.
But now there is requirement to read this excel file.
I am getting all the values as NULL because it is protected.
( I haven't placed any password yet in the code to protect the sheet, there is only one sheet in the excel file.)
I have got below code from my Search to unprotect the worksheet.
workSheet.RemoveAllChildren<SheetProtection>();
But, this is not working. I am still getting the null values while reading this protected sheet.
using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(FilePath, false))
{
WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
//if ((sheets.Count() != 2) && (sheets.First().Name.Value != "StudentNomination") && (sheets.Last().Name.Value != "Sheet2"))
//{
// throw new Exception("Please Upload the correct Nomination file, for example you can download the Nomination Template file first.!!");
//}
string relationshipId = sheets.First().Id.Value;
WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
Worksheet workSheet = worksheetPart.Worksheet;
workSheet.RemoveAllChildren<SheetProtection>();
SheetData sheetData = workSheet.GetFirstChild<SheetData>();
IEnumerable<Row> rows = sheetData.Descendants<Row>();
Can anyone Please help me on this?
回答1:
Your code for removing protection is correct. But before that you have to open the Excel file in Edit Mode. The second argument in SpreadSheetDocument.Open
should be set to true
.
Also Regardless of protection, you should be able to read a cell's value. See the below code. In order to test this you would have to create a excel file and fill the cells A1,B1 and C1 with numbers.
using System.Linq;
using System.Collections.Generic;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
class Test
{
static void Main()
{
string filePath = @"E:\test.xlsx";
using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(filePath, true))
{
WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
string relationshipId = sheets.First().Id.Value;
WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
Worksheet workSheet = worksheetPart.Worksheet;
var dataBeforeProtection = workSheet.Descendants<Row>().First().Descendants<Cell>().First().CellValue.InnerText;
workSheet.RemoveAllChildren<SheetProtection>();
var dataAfterProtection = workSheet.Descendants<Row>().First().Descendants<Cell>().First().CellValue.InnerText;
workSheet.Save();
}
}
}
来源:https://stackoverflow.com/questions/16642952/how-to-unprotect-sheet-using-openxml-code