Epplus linq sub grids in excel - c#

I guess I have been going about this wrong or wording it incorrectly.
I have a Controller with a LINQ query that returns a list and contained within it is a child list for each item. I am using EPPlus to create a excel doc for it and so far it works until I want to add to child list.
What i am looking to do is have a expand option for each row item that expands to the sub list within each item. Below is the code I have so far.
Controller (I chopped this up for the example here so if anything looks off its just because of the hack and job. Results.ToList() was actually a rather long LINQ query.
[HttpGet]
[Route("Download")]
public FileContentResult Download(int? mid)
{
using (var package = new ExcelPackage())
{
byte[] fileContents;
using (var ctx = new dbEntities())
{
results.ToList();
var merchantIdList = (results.GroupBy(t => t.DomainMerchantID, t => t.violations)
.OrderBy(g => g.Key)
.Select(g => g.Key).ToList());
var resultList = new List<ViolationsByMerchant>();
foreach (int? id in merchantIdList)
{
var thisResult = (from r in results
where r.violations.DomainMerchantID == id
orderby r.violations.DateOfInfraction descending
select new ViolationsByMerchant
{
SellerDomain = r.DomainName,
Merchant = r.IdentifierNiceName,
Contact = r.str_Name,
Phone = r.str_Phone,
AccountMatch = "????",
ViolationsProductDetails = from v in results
where v.violations.DomainMerchantID == id
select new ViolationsProductDetails()
{
ProductName = r.memberProducts.ProductName,
ProductLine = r.memberProducts.ProductLine,
Category = r.memberProducts.ProductCategory
}
}).FirstOrDefault();
resultList.Add(thisResult);
}
var worksheet = package.Workbook.Worksheets.Add("Merchant Violations");
int i = 1;
foreach (var item in resultList)
{
worksheet.Cells["A1:Z1"].Style.Font.Size = 15;
worksheet.Cells.AutoFitColumns();
worksheet.Cells["A1:Z1"].Style.Font.Bold = true;
worksheet.Cells[1, 1].Value = "Merchant";
worksheet.Cells["A" + i].Value = item.Merchant;
worksheet.Cells[1, 2].Value = "Account Match";
worksheet.Cells["B" + i].Value = item.AccountMatch;
worksheet.Cells[1, 3].Value = "Seller";
worksheet.Cells["C" + i].Value = item.SellerDomain;
worksheet.Cells[1, 4].Value = "Contact";
worksheet.Cells["D" + i].Value = item.Contact;
worksheet.Cells[1, 5].Value = "Phone";
worksheet.Cells["E" + i].Value = item.Phone;
i++;
}
fileContents = package.GetAsByteArray();
}
return File(
fileContents: fileContents,
contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
fileDownloadName: "MyMappProducts.xlsx"
);
}
}
LINQ Returns something like this if that helps.
{
"merchant": "Foo Merchant,
"accountMatch": "True",
"sellerDomain": "Amazon",
"contact": "John Doe",
"phone": "555-555-5555
"violationsProductDetails": [
{
"productName": "King Kong",
"productLine": "Animal",
"category": "King of the jungle",
},
{
"productName": "Prime",
"productLine": "Transformers",
"category": "Toy",
},
}

Related

Change for loop to forEach

I am working on a inventory updating program in vs2022 which I am using Gembox Spreadsheet for, It is working right now, but the boss man would like me to try to convert my for loop to a for each loop. The loop is what I am using to update my file.
Current For Loop
public void updateFile(string filename, int range, ItemLine selectedItem, decimal outValue)
{
var fullPath = $".\\Backend Files\\{filename}";
SpreadsheetInfo.SetLicense("FREE -LIMITED-KEY");
var workbook = ExcelFile.Load(fullPath, new CsvLoadOptions(CsvType.CommaDelimited));
var worksheet = workbook.Worksheets[0];
//foreach (var row in worksheet.Rows.Skip(1))
//{
// foreach (var cell in row.AllocatedCells)
// {
// string updateValue =
// if(cell.Value == int.TryParse((int)outValue, out int updateValue))
// {
// }
// }
//}
for (int i = 1; i <= range; i++)
{
var plan = worksheet.Rows[i].Cells[0].Value;
var desc = worksheet.Rows[i].Cells[1].Value;
var csvDescription = plan + " - " + desc;
var platedescription = plan + " - ";
if (selectedItem.ComboDescription == csvDescription)
{
worksheet.Rows[i].Cells[2].Value = selectedItem.Quantity;
}
if (selectedItem.plateDescription == platedescription)
{
worksheet.Rows[i].Cells[1].Value = selectedItem.Quantity;
}
}
workbook.Save(fullPath, new CsvSaveOptions(CsvType.CommaDelimited));
}
I beleive the forEach would look similar to this
private static List<ItemLine> ReadFile(string fileName, string defaultValueDescription)
{
string path = $".\\Backend Files\\{fileName}";
SpreadsheetInfo.SetLicense("FREE -LIMITED-KEY");
var workbook = ExcelFile.Load(path, new CsvLoadOptions(CsvType.CommaDelimited));
var worksheet = workbook.Worksheets[0];
var items = new List<ItemLine>();
items.Add(new ItemLine { Description = defaultValueDescription, Quantity = 0 });
foreach (var row in worksheet.Rows.Skip(1))
{
var cells = row.AllocatedCells;
var il = new ItemLine();
if (cells.Count == 2)
{
il.Description = cells[0].Value?.ToString() ?? "Description Not Found";
il.Quantity = cells[1].IntValue;
}
else if (cells.Count >= 3)
{
il.Plan = cells[0].Value?.ToString() ?? "Plan Not Found";
il.Description = cells[1].Value?.ToString() ?? "Description Not Found";
il.Quantity = cells[2].IntValue;
}
items.Add(il);
}
return items;
}

Problem with stock items, always returns 0 wsdl NetSuite c#

I try to return the stock of the items and I can not get it. Could someone guide me and tell me what I'm doing wrong?
This is my code, quantityAvailable is always 0 and location is null. This is an excerpt from my source code:
var recordRefs = new List<RecordRef>();
var ExternalIds = new List<string>();
ExternalIds.Add("REV0001");
ExternalIds.Add("REV0002");
foreach (string externalId in ExternalIds)
{
recordRefs.Add(new RecordRef
{
externalId = externalId,
type = RecordType.InventoryItem,
typeSpecified = true
});
}
var request1 = new ItemSearchBasic
{
externalId = new SearchMultiSelectField
{
#operator = SearchMultiSelectFieldOperator.anyOf,
operatorSpecified = true,
searchValue = recordRefs.ToArray()
}
};
SearchResult response = Client.Service.search(request1);
if (response.status.isSuccess)
{
if (response.totalRecords > 1)
{
Record[] records;
records = response.recordList;
for (int lcv = 0; lcv <= records.Length - 1; lcv++)
{
if (records[lcv].GetType().Name == "InventoryItem")
{
Console.WriteLine(((InventoryItem)records[lcv]).itemId);
Console.WriteLine(((InventoryItem)records[lcv]).internalId);
Console.WriteLine(((InventoryItem)records[lcv]).quantityAvailable);
Console.WriteLine(((InventoryItem)records[lcv]).averageCost);
}
}
}
}

Asp .Net Core 3.1 return File from controller on new MS Edge takes forever to download

this is just a handler to download an excel of data that comes from database, i even tried use debugger and everything goes fine. On chrome or firefox it file appears on downloads as soon as i click the button, but on the new MS Edge, it takes from 10 to 20 or more seconds until it starts downloading? Why???
public async Task<FileResult> OnGetDownloadExcel(int id)
{
var inventarios = await _context.Localizations
.Where(l => l.InventoryRecordId == id)
.Select(ir => new
{
ir.InventoryRecord.Id,
Armazem = ir.InventoryRecord.Warehouse.Name,
Colaborador = ir.InventoryRecord.User.Name,
ir.InventoryRecord.CreationDate,
ir.InventoryRecord.ClosedDate,
ir.InventoryRecord.Warehouse.Objective,
Resultado = (ir.InventoryRecord.Localizations.Sum(l => l.Precision) / ir.InventoryRecord.Localizations.Count()) * 100,
Localizacao = ir.Name,
ir.LabelsMissing,
ir.LabelsStored,
ir.Precision,
ir.Labels
})
.AsNoTracking()
.ToListAsync();
var comlumHeadrs = new string[]
{
"Id",
"Armazém",
"Colaborador",
"Criado Em",
"Finalizado Em",
"Objectivo",
"Resultado Final",
"Localização",
"Etiquetas Por Inventariar",
"Etiquetas Inventariadas",
"Precisão",
"Referência",
"Etiqueta Não Encontrada"
};
byte[] result;
using (var package = new ExcelPackage())
{
// add a new worksheet to the empty workbook
var worksheet = package.Workbook.Worksheets.Add("Inventário"); //Worksheet name
using (var cells = worksheet.Cells[1, 1, 1, 13]) //(1,1) (1,6)
{
cells.Style.Font.Bold = true;
}
//First add the headers
for (var i = 0; i < comlumHeadrs.Count(); i++)
{
worksheet.Cells[1, i + 1].Value = comlumHeadrs[i];
}
//Add values
var j = 2;
foreach (var item in inventarios)
{
if (item.Labels.Count() != 0)
{
foreach (var etiqueta in item.Labels)
{
worksheet.Cells[$"A{j}"].Value = item.Id;
worksheet.Cells[$"B{j}"].Value = item.Armazem;
worksheet.Cells[$"C{j}"].Value = item.Colaborador;
worksheet.Cells[$"D{j}"].Value = item.CreationDate.ToString("dd-mm-yyyy");
worksheet.Cells[$"E{j}"].Value = item.ClosedDate.Value.ToString("dd-mm-yyyy");
worksheet.Cells[$"F{j}"].Value = item.Objective;
worksheet.Cells[$"G{j}"].Value = item.Resultado;
worksheet.Cells[$"H{j}"].Value = item.Localizacao;
worksheet.Cells[$"I{j}"].Value = item.LabelsMissing;
worksheet.Cells[$"J{j}"].Value = item.LabelsStored;
worksheet.Cells[$"K{j}"].Value = item.Precision * 100;
worksheet.Cells[$"L{j}"].Value = etiqueta.Reference;
worksheet.Cells[$"M{j}"].Value = etiqueta.Name;
j++;
}
}
else
{
worksheet.Cells[$"A{j}"].Value = item.Id;
worksheet.Cells[$"B{j}"].Value = item.Armazem;
worksheet.Cells[$"C{j}"].Value = item.Colaborador;
worksheet.Cells[$"D{j}"].Value = item.CreationDate.ToString("dd-mm-yyyy");
worksheet.Cells[$"E{j}"].Value = item.ClosedDate.Value.ToString("dd-mm-yyyy");
worksheet.Cells[$"F{j}"].Value = item.Objective;
worksheet.Cells[$"G{j}"].Value = item.Resultado;
worksheet.Cells[$"H{j}"].Value = item.Localizacao;
worksheet.Cells[$"I{j}"].Value = item.LabelsMissing;
worksheet.Cells[$"J{j}"].Value = item.LabelsStored;
worksheet.Cells[$"K{j}"].Value = item.Precision * 100;
worksheet.Cells[$"L{j}"].Value = "";
worksheet.Cells[$"M{j}"].Value = "";
j++;
}
}
result = package.GetAsByteArray();
}
return File(result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml", $"inventario{id}.xlsx");
}
EDIT
here is my edge version
Version 80.0.361.66 (Official build) (64-bit)
either way, maybe this is not the right place to ask about this, but i don't know where can i report problems with Edge
this image is when i click the button, and the request is the last item at the bottom, as you can see there is no problem.

C# ExcelDataReader read from specific columns only

i'm trying to get data from my excel sheet to add it into database which works perfectly but i only want the data under specific headers.
Here is my config code:
var headers = new List<string>;
DataSet result = excelDataReader.AsDataSet(new ExcelDataSetConfiguration()
{
ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
{
UseHeaderRow = true,
ReadHeaderRow = rowReader =>
{
for (var i = 0; i < rowReader.FieldCount; i++)
headers.Add(Convert.ToString(rowReader.GetValue(i)));
},
FilterColumn = (columnReader, columnIndex) =>
headers.IndexOf("LOCATION") == columnIndex
|| headers.IndexOf("PARENT") == columnIndex
|| headers.IndexOf("DESCRIPTION") == columnIndex
}
});
LOCATION,PARENT and DESCRIPTION are the columns header names.
and here is the code i'm using to add the data to database
foreach (DataTable table in result.Tables)
{
foreach (DataRow row in table.Rows)
{
if (!existedLocations.Any(l => l.ShortCode?.Replace(" ", String.Empty) == row[0].ToString().Replace(" ", String.Empty)))
{
addtable.Name = addtable.NameAr = row[2].ToString().Substring(row[2].ToString().LastIndexOf(',') + 1);
addtable.ParentLocation = connection.Locations.FirstOrDefault(l => l.ShortCode == row[1].ToString()).Id;
addtable.LocationType = (int)LocationsTypes.Area;
addtable.ShortCode = row[0].ToString();
addtable.Category = (int)LocationsCategory.indoor;
addtable.IsActive = 1;
addtable.Isdeleted = 0;
existedLocations.Add(addtable);
connection.Locations.InsertOnSubmit(addtable);
connection.SubmitChanges();
addtable = new Location();
}
}
}
the sheets headers is defined as following
sheet1
sheet2
Well, you have two sheets, with the same headers but in different position. Your code is adding the headers of the first sheet to the list and then the ones from the second sheet. So, when you look for the headers to filter in the second sheet, you get the indexes from the first one, as IndexOf will get the first occurence.
Also, it appears that you're only using headers list to filter the columns, so you can simplify:
var result = reader.AsDataSet(new ExcelDataSetConfiguration()
{
ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
{
UseHeaderRow = true,
FilterColumn = (columnReader, columnIndex) =>
{
string header = columnReader.GetString(columnIndex);
return (header == "LOCATION" ||
header == "PARENT" ||
header == "DESCRIPTION"
);
}
}
});

Create Pivot Table Filters With EPPLUS

I am using EPPLUS excel library. Do you have an idea how to create pivot table with report filters, row label and values ? Some simple example will be excellent.
Here is a simple example. Note that EEPlus does not have the ability to do page filters so you will have to use (in order of difficulty) VBA, Excel Interop, or XML manipulation (I used XML below). You can put this code into a unit test of the EPPlus source download for easy testing:
const string FORMATCURRENCY = "#,###;[Red](#,###)";
var file = new FileInfo(#"c:\temp\temp.xlsx");
if (file.Exists)
file.Delete();
var pck = new ExcelPackage(file);
var workbook = pck.Workbook;
var worksheet = workbook.Worksheets.Add("newsheet");
//The data
worksheet.Cells["A20"].Value = "Col1";
worksheet.Cells["A21"].Value = "sdf";
worksheet.Cells["A22"].Value = "wer";
worksheet.Cells["A23"].Value = "ghgh";
worksheet.Cells["A24"].Value = "sdf";
worksheet.Cells["A25"].Value = "wer";
worksheet.Cells["A26"].Value = "ghgh";
worksheet.Cells["A27"].Value = "sdf";
worksheet.Cells["A28"].Value = "wer";
worksheet.Cells["A29"].Value = "ghgh";
worksheet.Cells["B20"].Value = "Col2";
worksheet.Cells["B21"].Value = "Group A";
worksheet.Cells["B22"].Value = "Group B";
worksheet.Cells["B23"].Value = "Group A";
worksheet.Cells["B24"].Value = "Group C";
worksheet.Cells["B25"].Value = "Group A";
worksheet.Cells["B26"].Value = "Group B";
worksheet.Cells["B27"].Value = "Group C";
worksheet.Cells["B28"].Value = "Group C";
worksheet.Cells["B29"].Value = "Group A";
worksheet.Cells["C20"].Value = "Col3";
worksheet.Cells["C21"].Value = 453;
worksheet.Cells["C22"].Value = 634;
worksheet.Cells["C23"].Value = 274;
worksheet.Cells["C24"].Value = 453;
worksheet.Cells["C25"].Value = 634;
worksheet.Cells["C26"].Value = 274;
worksheet.Cells["C27"].Value = 453;
worksheet.Cells["C28"].Value = 634;
worksheet.Cells["C29"].Value = 274;
worksheet.Cells["D20"].Value = "Col4";
worksheet.Cells["D21"].Value = 686468;
worksheet.Cells["D22"].Value = 996440;
worksheet.Cells["D23"].Value = 185780;
worksheet.Cells["D24"].Value = 686468;
worksheet.Cells["D25"].Value = 996440;
worksheet.Cells["D26"].Value = 185780;
worksheet.Cells["D27"].Value = 686468;
worksheet.Cells["D28"].Value = 996440;
worksheet.Cells["D29"].Value = 185780;
//The pivot table
var pivotTable = worksheet.PivotTables.Add(worksheet.Cells["A4"], worksheet.Cells["A20:D29"], "test");
//The label row field
pivotTable.RowFields.Add(pivotTable.Fields["Col1"]);
pivotTable.DataOnRows = false;
//The data fields
var field = pivotTable.DataFields.Add(pivotTable.Fields["Col3"]);
field.Name = "Sum of Col2";
field.Function = DataFieldFunctions.Sum;
field.Format = FORMATCURRENCY;
field = pivotTable.DataFields.Add(pivotTable.Fields["Col4"]);
field.Name = "Sum of Col3";
field.Function = DataFieldFunctions.Sum;
field.Format = FORMATCURRENCY;
//The page field
pivotTable.PageFields.Add(pivotTable.Fields["Col2"]);
var xdCacheDefinition = pivotTable.CacheDefinition.CacheDefinitionXml;
var xeCacheFields = xdCacheDefinition.FirstChild["cacheFields"];
if (xeCacheFields == null)
return;
//To filter, add items to the Cache Definition via XML
var count = 0;
var assetfieldidx = -1;
foreach (XmlElement cField in xeCacheFields)
{
var att = cField.Attributes["name"];
if (att != null && att.Value == "Col2" )
{
assetfieldidx = count;
var sharedItems = cField.GetElementsByTagName("sharedItems")[0] as XmlElement;
if(sharedItems == null)
continue;
//set the collection attributes
sharedItems.RemoveAllAttributes();
att = xdCacheDefinition.CreateAttribute("count");
att.Value = "3";
sharedItems.Attributes.Append(att);
//create and add the item
var item = xdCacheDefinition.CreateElement("s", sharedItems.NamespaceURI);
att = xdCacheDefinition.CreateAttribute("v");
att.Value = "Group A";
item.Attributes.Append(att);
sharedItems.AppendChild(item);
item = xdCacheDefinition.CreateElement("s", sharedItems.NamespaceURI);
att = xdCacheDefinition.CreateAttribute("v");
att.Value = "Group B";
item.Attributes.Append(att);
sharedItems.AppendChild(item);
item = xdCacheDefinition.CreateElement("s", sharedItems.NamespaceURI);
att = xdCacheDefinition.CreateAttribute("v");
att.Value = "Group C";
item.Attributes.Append(att);
sharedItems.AppendChild(item);
break;
}
count++;
}
//Now go back to the main pivot table xml and add the cross references to complete filtering
var xdPivotTable = pivotTable.PivotTableXml;
var xdPivotFields = xdPivotTable.FirstChild["pivotFields"];
if (xdPivotFields == null)
return;
count = 0;
foreach (XmlElement pField in xdPivotFields)
{
//Find the asset type field
if (count == assetfieldidx)
{
var att = xdPivotTable.CreateAttribute("multipleItemSelectionAllowed");
att.Value = "1";
pField.Attributes.Append(att);
var items = pField.GetElementsByTagName("items")[0] as XmlElement;
items.RemoveAll();
att = xdPivotTable.CreateAttribute("count");
att.Value = "4";
items.Attributes.Append(att);
pField.AppendChild(items);
//Add the classes to the fields item collection
for (var i = 0; i < 3; i++)
{
var item = xdPivotTable.CreateElement("item", items.NamespaceURI);
att = xdPivotTable.CreateAttribute("x");
att.Value = i.ToString(CultureInfo.InvariantCulture);
item.Attributes.Append(att);
//Turn of the Cash class in the fielder
if (i == 1)
{
att = xdPivotTable.CreateAttribute("h");
att.Value = "1";
item.Attributes.Append(att);
}
items.AppendChild(item);
}
//Add the default
var defaultitem = xdPivotTable.CreateElement("item", items.NamespaceURI);
att = xdPivotTable.CreateAttribute("t");
att.Value = "default";
defaultitem.Attributes.Append(att);
items.AppendChild(defaultitem);
break;
}
count++;
}
pck.Save();
Sorry for all the edit but I have been working on this for a little while when I stumbled on this question. I created an extension method just for applying a filter. Give it the field name (it assumes there is a header line contining the column names), the filters you want to apply, and the worksheet containing the data or it will just the Pivot Table worksheet if no data worksheet is passed in. It have done basic testing so you should QA:
public static bool FilterField(this ExcelPivotTable pivotTable, string pageFieldName, IEnumerable<object> filters, ExcelWorksheet dataWorksheet = null)
{
//set the worksheet
var ws = dataWorksheet ?? pivotTable.WorkSheet;
//Set the cache definitions and cache fields
var xdCacheDefinition = pivotTable.CacheDefinition.CacheDefinitionXml;
var xeCacheFields = xdCacheDefinition.FirstChild["cacheFields"];
if (xeCacheFields == null)
return false;
//Go the field list in the definitions, note the field idx and valuesfor
var count = 0;
var fieldIndex = -1;
List<object> fieldValues = null;
foreach (XmlElement cField in xeCacheFields)
{
var att = cField.Attributes["name"];
if (att != null && att.Value.Equals(pageFieldName, StringComparison.OrdinalIgnoreCase))
{
//store the field data
fieldIndex = count;
var dataddress = new ExcelAddress(pivotTable.CacheDefinition.SourceRange.Address);
var valueHeader = ws
.Cells[dataddress.Start.Row, dataddress.Start.Column, dataddress.Start.Row, dataddress.End.Column]
.FirstOrDefault(cell => cell.Value.ToString().Equals(pageFieldName, StringComparison.OrdinalIgnoreCase));
if (valueHeader == null)
return false;
//Get the range minus the header row
var valueObject = valueHeader.Offset(1, 0, dataddress.End.Row - dataddress.Start.Row, 1).Value;
var values = (object[,])valueObject;
fieldValues = values
.Cast<object>()
.Distinct()
.ToList();
//kick back if the types are mixed
if (fieldValues.FirstOrDefault(v => v is string) != null && fieldValues.FirstOrDefault(v => !(v is string)) != null)
throw new NotImplementedException("Filter function does not (yet) support mixed parameter types");
//fill in the shared items for the field
var sharedItems = cField.GetElementsByTagName("sharedItems")[0] as XmlElement;
if (sharedItems == null)
continue;
//Reset the collection attributes
sharedItems.RemoveAllAttributes();
//Handle numerics - assume all or nothing
var isNumeric = fieldValues.FirstOrDefault(v => v is string) == null;
if (isNumeric)
{
att = xdCacheDefinition.CreateAttribute("containsSemiMixedTypes");
att.Value = "0";
sharedItems.Attributes.Append(att);
att = xdCacheDefinition.CreateAttribute("containsString");
att.Value = "0";
sharedItems.Attributes.Append(att);
att = xdCacheDefinition.CreateAttribute("containsNumber");
att.Value = "1";
sharedItems.Attributes.Append(att);
att = xdCacheDefinition.CreateAttribute("containsInteger");
att.Value = fieldValues.Any(v => !(v is int || v is long)) ? "0" : "1";
sharedItems.Attributes.Append(att);
}
//add the count
att = xdCacheDefinition.CreateAttribute("count");
att.Value = fieldValues.Count.ToString(CultureInfo.InvariantCulture);
sharedItems.Attributes.Append(att);
//create and add the item
foreach (var fieldvalue in fieldValues)
{
var item = xdCacheDefinition.CreateElement(isNumeric ? "n" : "s", sharedItems.NamespaceURI);
att = xdCacheDefinition.CreateAttribute("v");
att.Value = fieldvalue.ToString();
item.Attributes.Append(att);
sharedItems.AppendChild(item);
}
break;
}
count++;
}
if (fieldIndex == -1 || fieldValues == null)
return false;
//Now go back to the main pivot table xml and add the cross references to complete filtering
var xdPivotTable = pivotTable.PivotTableXml;
var xdPivotFields = xdPivotTable.FirstChild["pivotFields"];
if (xdPivotFields == null)
return false;
var filtervalues = filters.ToList();
count = 0;
foreach (XmlElement pField in xdPivotFields)
{
//Find the asset type field
if (count == fieldIndex)
{
var att = xdPivotTable.CreateAttribute("multipleItemSelectionAllowed");
att.Value = "1";
pField.Attributes.Append(att);
var items = pField.GetElementsByTagName("items")[0] as XmlElement;
if (items == null)
return false;
items.RemoveAll();
att = xdPivotTable.CreateAttribute("count");
att.Value = (fieldValues.Count + 1).ToString(CultureInfo.InvariantCulture);
items.Attributes.Append(att);
pField.AppendChild(items);
//Add the classes to the fields item collection
for (var i = 0; i < fieldValues.Count; i++)
{
var item = xdPivotTable.CreateElement("item", items.NamespaceURI);
att = xdPivotTable.CreateAttribute("x");
att.Value = i.ToString(CultureInfo.InvariantCulture);
item.Attributes.Append(att);
if (filtervalues.Contains(fieldValues[i]))
{
att = xdPivotTable.CreateAttribute("h");
att.Value = "1";
item.Attributes.Append(att);
}
items.AppendChild(item);
}
//Add the default
var defaultitem = xdPivotTable.CreateElement("item", items.NamespaceURI);
att = xdPivotTable.CreateAttribute("t");
att.Value = "default";
defaultitem.Attributes.Append(att);
items.AppendChild(defaultitem);
break;
}
count++;
}
return true;
}
To use it in the above example, you would do something like this:
pivotTable.FilterField("Col2", new List<string> { "Group B" });

Categories