我使用Open XML 2.19在powershell中创建了一个XLSX文件。现在我尝试将自动筛选器附加到第一行。
在Microsoft文档中,工作表具有自动筛选设置。但是我的$sheet
没有这样的属性或方法。
我需要直接操作XML结构还是有其他方法来设置自动筛选器?
编辑:
我发现最有希望的方法是在这里,但我的$spreadsheetDocument
中没有GetPreceedingElement
public static void ApplyAutofilter(string fileName, string sheetName, string reference)
{
using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, true))
{
IEnumerable<Sheet> sheets = document.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>().Where(s => s.Name == sheetName);
var arrSheets = sheets as Sheet[] ?? sheets.ToArray();
string relationshipId = arrSheets.First().Id.Value;
var worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(relationshipId);
var autoFilter = new AutoFilter() { Reference = reference };
OpenXmlElement preceedingElement = GetPreceedingElement(worksheetPart);
worksheetPart.Worksheet.InsertAfter(autoFilter, preceedingElement);
worksheetPart.Worksheet.Save();
}
}
我终于知道为什么它不起作用了。
ObenXML知道两个不同的表单
$workSheet = New-Object DocumentFormat.OpenXml.Spreadsheet.Worksheet
和
$sheet = New-Object DocumentFormat.OpenXml.Spreadsheet.Sheet
$workSheet不需要显式定义。我是这样做的:
$worksheetPart = Invoke-GenericMethod -InputObject $workbookpart -MethodName AddNewPart -GenericType DocumentFormat.OpenXml.Packaging.WorksheetPart
$sheet = New-Object DocumentFormat.OpenXml.Spreadsheet.Sheet
$sheet.Id = $spreadsheetDocument.WorkbookPart.GetIdOfPart($worksheetPart)
$sheet.SheetId = New-Object DocumentFormat.OpenXml.UInt32Value $sheetNo
$sheet.Name = "$sheetName"
$sheets.Append($sheet)
$sheetData = New-Object DocumentFormat.OpenXml.Spreadsheet.SheetData
$worksheetPart.Worksheet = New-Object DocumentFormat.OpenXml.Spreadsheet.Worksheet($sheetData)
在这种情况下,过滤器必须应用于Sheetpart
的Worksheet
属性
$autoFilter = New-Object DocumentFormat.OpenXml.Spreadsheet.AutoFilter
$autoFilter.Reference = "A1:Y1"
$worksheetPart.Worksheet.Append($autoFilter)