TerritoryGroup = st.[Group], TerritoryName = st.Name, SalesPerson = pp.FirstName + ' ' + pp.LastName, soh.OrderDate, ProductCategory = pc.Name, ProductSubcategory = psc.Name, Product = p.Name, sod.OrderQty, sod.UnitPriceDiscount, Discount = (sod.OrderQty * sod.UnitPrice * sod.UnitPriceDiscount), sod.UnitPrice, sod.LineTotal from Sales.SalesOrderDetail sod inner join Sales.SalesOrderHeader soh on sod.SalesOrderID = soh.SalesOrderID inner join Sales.SalesPerson sp on soh.SalesPersonID = sp.BusinessEntityID inner join Person.Person pp on sp.BusinessEntityID = pp.BusinessEntityID inner join Sales.SalesTerritory st on sp.TerritoryID = st.TerritoryID inner join Production.Product p on sod.ProductID = p.ProductID inner join Production.ProductSubcategory psc on p.ProductSubcategoryID = psc.ProductSubcategoryID inner join Production.ProductCategory pc on psc.ProductCategoryID = pc.ProductCategoryID where soh.OnlineOrderFlag = 0 and soh.Status = 5
public class DataRow { public string TerritoryGroup { get; set; } public string TerritoryName { get; set; } public string SalesPerson { get; set; } public DateTime OrderDate { get; set; } public string ProductCategory { get; set; } public string ProductSubcategory { get; set; } public string Product { get; set; } public short OrderQty { get; set; } public decimal UnitPriceDiscount { get; set; } public decimal Discount { get; set; } public decimal UnitPrice { get; set; } public decimal LineTotal { get; set; } public int OrderYear { get { return OrderDate.Year; } } public int OrderMonth { get { return OrderDate.Month; } } }
// number formats string positiveFormat = "#,##0.00_)"; string negativeFormat = "(#,##0.00)"; string zeroFormat = "-_)"; string numberFormat = positiveFormat + ";" + negativeFormat; string fullNumberFormat = positiveFormat + ";" + negativeFormat + ";" + zeroFormat;
// rows and columns indices int startRowIndex = 2; int territoryNameIndex = 2; int salesPersonIndex = 3; int orderYearIndex = 4; int orderMonthFromIndex = 5; int orderMonthToIndex = 16; int totalIndex = 17;
// package var ep = new ExcelPackage(); // workbook var wb = ep.Workbook; // group on territory group var territoryGroups = data.GroupBy(d => d.TerritoryGroup).OrderBy(g => g.Key); // create new worksheet for every territory group foreach (var territoryGroup in territoryGroups) { // new worksheet var ws = wb.Worksheets.Add(territoryGroup.Key);
int rowIndex = startRowIndex; // headers ws.Cells[rowIndex, territoryNameIndex].Value = "Territory"; ws.Cells[rowIndex, salesPersonIndex].Value = "Salesperson"; ws.Cells[rowIndex, orderYearIndex].Value = "Order Year"; ws.Cells[rowIndex, totalIndex].Value = "Total"; // month headers CultureInfo enUS = CultureInfo.CreateSpecificCulture("en-US"); for (int month = 1; month <= 12; month++) { string value = new DateTime(1900, month, 1).ToString("MMM", enUS); ws.Cells[rowIndex, month - 1 + orderMonthFromIndex].Value = value; } rowIndex++;
// group on salesperson, territory var salesPersonGroups = territoryGroup .GroupBy(d => new { d.SalesPerson, d.TerritoryName }) .OrderBy(g => g.Key.SalesPerson); // the index of the first data row, after the header row int fromRowIndex = rowIndex; foreach (var salesPersonGroup in salesPersonGroups) {
// group on order year // sort descending var orderYearGroups = salesPersonGroup .GroupBy(g => g.OrderDate.Year) .OrderByDescending(g => g.Key); foreach (var orderYearGroup in orderYearGroups) { // territory string territoryName = salesPersonGroup.Key.TerritoryName; ws.Cells[rowIndex, territoryNameIndex].Value = territoryName; // salesperson string salesperson = salesPersonGroup.Key.SalesPerson; ws.Cells[rowIndex, salesPersonIndex].Value = salesperson; // order year int orderYear = orderYearGroup.Key; ws.Cells[rowIndex, orderYearIndex].Value = orderYear;
// for all the months, set the default value to 0 // in case there is no data for this salesperson-year-month ws.Cells[rowIndex, orderMonthFromIndex, rowIndex, orderMonthToIndex].Value = 0; // group on order month var orderMonthGroups = orderYearGroup.GroupBy(g => g.OrderDate.Month); // revenues foreach (var orderMonthGroup in orderMonthGroups) { // sum the line total over all the orders for this salesperson-year-month decimal total = orderMonthGroup.Sum(d => d.LineTotal); int orderMonth = orderMonthGroup.Key; ws.Cells[rowIndex, orderMonth - 1 + orderMonthFromIndex].Value = total; }<sxh> * The total column is the summation of revenues over the current row from January to December. * <sxh C#> // total column string totalColumnAddress = ExcelCellBase.GetAddress( rowIndex, orderMonthFromIndex, rowIndex, orderMonthToIndex ); ws.Cells[rowIndex, totalIndex].Formula = string.Format("SUM({0})", totalColumnAddress); rowIndex++; }
// the index of the last data row, before the total row int toRowIndex = rowIndex - 1; // cells format ws.Cells[ fromRowIndex, orderMonthFromIndex, toRowIndex, totalIndex ].Style.Numberformat.Format = fullNumberFormat; // #,##0.00_);(#,##0.00);-_)
// total row header ws.Cells[rowIndex, territoryNameIndex].Value = "Total"; // total row - per month for (int columnIndex = orderMonthFromIndex; columnIndex <= totalIndex; columnIndex++) { string totalMonthAddress = ExcelCellBase.GetAddress( fromRowIndex, columnIndex, toRowIndex, columnIndex ); ws.Cells[rowIndex, columnIndex].Formula = string.Format("SUM({0})", totalMonthAddress); } // total row - all (bottom-right cell of the table) string totalAddress = ExcelCellBase.GetAddress( rowIndex, orderMonthFromIndex, rowIndex, orderMonthToIndex ); ws.Cells[rowIndex, totalIndex].Formula = string.Format("SUM({0})", totalAddress); // total cells format ws.Cells[ rowIndex, orderMonthFromIndex, rowIndex, totalIndex ].Style.Numberformat.Format = numberFormat; // #,##0.00_);(#,##0.00) } }
// group on territory group var territoryGroups = data.GroupBy(d => d.TerritoryGroup).OrderBy(g => g.Key); // the starting color is (0, 0, 154) int greenStep = 255 / territoryGroups.Count(); int blueStep = (255 - 154) / territoryGroups.Count(); int territoryGroupIndex = 0; foreach (var territoryGroup in territoryGroups) { // new worksheet var ws = wb.Worksheets.Add(territoryGroup.Key); // tab color int green = (territoryGroupIndex * greenStep); int blue = (territoryGroupIndex * blueStep) + 154; ws.TabColor = System.Drawing.Color.FromArgb(0, green, blue); territoryGroupIndex++; }
// group on salesperson, territory var salesPersonGroups = territoryGroup .GroupBy(d => new { d.SalesPerson, d.TerritoryName }) .OrderBy(g => g.Key.SalesPerson); foreach (var salesPersonGroup in salesPersonGroups) { int salesPersonFromRowIndex = rowIndex; // group on order year // sort descending var orderYearGroups = salesPersonGroup .GroupBy(g => g.OrderDate.Year) .OrderByDescending(g => g.Key); foreach (var orderYearGroup in orderYearGroups) { // add row for each order year rowIndex++; } int salesPersonToRowIndex = rowIndex - 1; // sub total row ws.Cells[rowIndex, territoryNameIndex].Value = salesPersonGroup.Key.TerritoryName; ws.Cells[rowIndex, salesPersonIndex].Value = salesPersonGroup.Key.SalesPerson; ws.Cells[rowIndex, orderYearIndex].Value = "S. Total"; // sub total for each order month for (int columnIndex = orderMonthFromIndex; columnIndex <= orderMonthToIndex; columnIndex++) { using (var cells = ws.Cells[rowIndex, columnIndex]) { string subtotalAddress = ExcelCellBase.GetAddress( salesPersonFromRowIndex, columnIndex, salesPersonToRowIndex, columnIndex ); cells.Formula = string.Format("SUBTOTAL(9,{0})", subtotalAddress); cells.Style.Numberformat.Format = numberFormat; // #,##0.00_);(#,##0.00) } } rowIndex++; }
// group on salesperson, territory var salesPersonGroups = territoryGroup .GroupBy(d => new { d.SalesPerson, d.TerritoryName }) .OrderBy(g => g.Key.SalesPerson); foreach (var salesPersonGroup in salesPersonGroups) { int salesPersonFromRowIndex = rowIndex; // group on order year // sort descending var orderYearGroups = salesPersonGroup .GroupBy(g => g.OrderDate.Year) .OrderByDescending(g => g.Key); foreach (var orderYearGroup in orderYearGroups) { // add row for each order year rowIndex++; } int salesPersonToRowIndex = rowIndex - 1; int subTotalRowIndex = rowIndex; // merge cells territory using (var cells = ws.Cells[ salesPersonFromRowIndex, territoryNameIndex, subTotalRowIndex, territoryNameIndex]) { cells.Merge = true; cells.Style.VerticalAlignment = ExcelVerticalAlignment.Center; } // merge cells salesperson using (var cells = ws.Cells[ salesPersonFromRowIndex, salesPersonIndex, subTotalRowIndex, salesPersonIndex]) { cells.Merge = true; cells.Style.VerticalAlignment = ExcelVerticalAlignment.Center; } rowIndex++; }
// rows and columns indices int startRowIndex = 2; int territoryNameIndex = 2; int totalIndex = 17; // rowIndex holds the current running row index int toRowIndex = rowIndex; using (ExcelRange autoFilterCells = ws.Cells[ startRowIndex, territoryNameIndex, toRowIndex, totalIndex]) { autoFilterCells.AutoFilter = true; }
// rows and columns indices int startRowIndex = 2; int orderMonthFromIndex = 5; // ws type is ExcelWorksheet ws.View.FreezePanes(startRowIndex + 1, orderMonthFromIndex); // E3
<x:autoFilter> <x:filterColumn colId="2"> </x:filterColumn> </x:autoFilter>
<x:autoFilter> <x:filterColumn colId="2"> <x:filters blank="true"> </x:filters> </x:filterColumn> </x:autoFilter>
<x:autoFilter> <x:filterColumn colId="2"> <x:filters blank="true"> <x:filter val="2014" /> <x:filter val="2013" /> <x:filter val="S. Total" /> </x:filters> </x:filterColumn> </x:autoFilter>
namespace System.Xml { public static partial class XmlExtensions { public static XmlElement AppendElement(this XmlNode parent, string namespace, string name) { var elm = parent.OwnerDocument.CreateElement(name, namespace); parent.AppendChild(elm); return elm; } public static XmlAttribute AppendAttribute(this XmlNode parent, string name, string value) { var att = parent.OwnerDocument.CreateAttribute(name); att.Value = value; parent.Attributes.Append(att); return att; } } }
// rows and columns indices int startRowIndex = 2; int territoryNameIndex = 2; int orderYearIndex = 4; int totalIndex = 17; // rowIndex holds the current running row index int toRowIndex = rowIndex; // order year column D int filterColumnIndex = orderYearIndex; // filters: current year 2014, previous year 2013, S. Total string[] filterValues = new string[] { "2014", "2013", "S. Total" }; // include (Blanks) bool blanks = true;
using (ExcelRange autoFilterCells = ws.Cells[ startRowIndex, territoryNameIndex, toRowIndex, totalIndex]) { // enable auto filter autoFilterCells.AutoFilter = true;
XmlDocument xdoc = autoFilterCells.Worksheet.WorksheetXml;
var nsm = new System.Xml.XmlNamespaceManager(xdoc.NameTable); // "http://schemas.openxmlformats.org/spreadsheetml/2006/main" var schemaMain = xdoc.DocumentElement.NamespaceURI; if (nsm.HasNamespace("x") == false) nsm.AddNamespace("x", schemaMain);
// <x:autoFilter> var autoFilter = xdoc.SelectSingleNode("/x:worksheet/x:autoFilter", nsm);
// <x:filterColumn colId="2"> var filterColumn = autoFilter.AppendElement(schemaMain, "x:filterColumn"); int colId = filterColumnIndex - autoFilterCells.Start.Column; filterColumn.AppendAttribute("colId", colId.ToString());
// <x:filters blank="true"> var filters = filterColumn.AppendElement(schemaMain, "x:filters"); if (blanks) filters.AppendAttribute("blank", "true");
// <x:filter val="filterValue" /> foreach (var filterValue in filterValues) { var filter = filters.AppendElement(schemaMain, "x:filter"); filter.AppendAttribute("val", filterValue); }
var filterCells = ws.Cells[ autoFilterCells.Start.Row + 1, filterColumnIndex, autoFilterCells.End.Row, filterColumnIndex ]; var cellValues = filterCells.Select(cell => new { Value = (cell.Value ?? string.Empty).ToString(), cell.Start.Row // row index });
var hiddenRows = cellValues .Where(c => filterValues.Contains(c.Value) == false) .Select(c => c.Row);
if (blanks) { hiddenRows = hiddenRows .Except(cellValues.Where(c => string.IsNullOrEmpty(c.Value)) .Select(c => c.Row)); }
hiddenRows = hiddenRows.OrderByDescending(r => r);
foreach (var row in hiddenRows) ws.Row(row).Hidden = true; }
// rows and columns indices int startRowIndex = 2; int territoryNameIndex = 2; int orderYearIndex = 4; int totalIndex = 17; // rowIndex holds the current running row index int toRowIndex = rowIndex; // order year column D int filterColumnIndex = orderYearIndex; // filters: current year 2014, previous year 2013, S. Total string[] filterValues = new string[] { "2014", "2013", "S. Total" }; // include (Blanks) bool blanks = true; using (ExcelRange autoFilterCells = ws.Cells[ startRowIndex, territoryNameIndex, toRowIndex, totalIndex]) { // enable auto filter autoFilterCells.AutoFilter = true; XmlDocument xdoc = autoFilterCells.Worksheet.WorksheetXml; var nsm = new System.Xml.XmlNamespaceManager(xdoc.NameTable); // "http://schemas.openxmlformats.org/spreadsheetml/2006/main" var schemaMain = xdoc.DocumentElement.NamespaceURI; if (nsm.HasNamespace("x") == false) nsm.AddNamespace("x", schemaMain); // <x:autoFilter> var autoFilter = xdoc.SelectSingleNode("/x:worksheet/x:autoFilter", nsm); // <x:filterColumn colId="2"> var filterColumn = autoFilter.AppendElement(schemaMain, "x:filterColumn"); int colId = filterColumnIndex - autoFilterCells.Start.Column; filterColumn.AppendAttribute("colId", colId.ToString()); // <x:filters blank="true"> var filters = filterColumn.AppendElement(schemaMain, "x:filters"); if (blanks) filters.AppendAttribute("blank", "true"); // <x:filter val="filterValue" /> foreach (var filterValue in filterValues) { var filter = filters.AppendElement(schemaMain, "x:filter"); filter.AppendAttribute("val", filterValue); } var filterCells = ws.Cells[ autoFilterCells.Start.Row + 1, filterColumnIndex, autoFilterCells.End.Row, filterColumnIndex ]; var cellValues = filterCells.Select(cell => new { Value = (cell.Value ?? string.Empty).ToString(), cell.Start.Row // row index }); var hiddenRows = cellValues .Where(c => filterValues.Contains(c.Value) == false) .Select(c => c.Row); if (blanks) { hiddenRows = hiddenRows .Except(cellValues.Where(c => string.IsNullOrEmpty(c.Value)) .Select(c => c.Row)); } hiddenRows = hiddenRows.OrderByDescending(r => r); // hide rows foreach (var row in hiddenRows) ws.Row(row).Hidden = true; }
// prefix "x" string schemaMain = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; // prefix "a" string schemaDrawings = "http://schemas.openxmlformats.org/drawingml/2006/main"; // prefix "c" string schemaChart = "http://schemas.openxmlformats.org/drawingml/2006/chart";
// rows and columns indices int startRowIndex = 2; int orderMonthFromIndex = 5; int orderMonthToIndex = 16; // group on territory group var territoryGroups = data.GroupBy(d => d.TerritoryGroup).OrderBy(g => g.Key); foreach (var territoryGroup in territoryGroups) { // new worksheet var ws = wb.Worksheets.Add(territoryGroup.Key); int rowIndex = startRowIndex; /* build the table up to the territory total rows */
// chart string chartTitle = territoryGroup.Key; ExcelBarChart chart = ws.Drawings.AddChart( "crt" + chartTitle.Replace(" ", string.Empty), eChartType.ColumnClustered ) as ExcelBarChart; // size chart.SetSize(1100, 500); // title chart.Title.Text = chartTitle; chart.Title.Font.Size = 18; chart.Title.Font.Bold = true; // legend position chart.Legend.Position = eLegendPosition.Bottom; // Y axis chart.YAxis.Font.Size = 9; chart.YAxis.Border.Fill.Style = eFillStyle.NoFill; // Y axis - display unit chart.YAxis.DisplayUnit = 1000; // K chart.YAxis.Format = "#,##0 K" + ";" + "(#,##0 K)"; // remove all tick marks chart.XAxis.MajorTickMark = eAxisTickMark.None; chart.XAxis.MinorTickMark = eAxisTickMark.None; chart.YAxis.MajorTickMark = eAxisTickMark.None; chart.YAxis.MinorTickMark = eAxisTickMark.None;
// group on territory var territoryNameGroups = territoryGroup.GroupBy(d => d.TerritoryName).OrderBy(g => g.Key); foreach (var territoryNameGroup in territoryNameGroups) { /* add territory total row */ // serie header (territory name) string serieHeader = territoryNameGroup.Key; // territory total row string serieAddress = ExcelCellBase.GetFullAddress( ws.Name, ExcelCellBase.GetAddress( rowIndex, orderMonthFromIndex, rowIndex, orderMonthToIndex ) ); // months row: Jan, Feb, Mar, ... string xSerieAddress = ExcelCellBase.GetFullAddress( ws.Name, ExcelCellBase.GetAddress( startRowIndex, orderMonthFromIndex, startRowIndex, orderMonthToIndex ) ); // add serie to chart chart.Series.Add(serieAddress, xSerieAddress).Header = serieHeader; rowIndex++; }
int toRowIndex = rowIndex - 1; // chart position int chartRow = toRowIndex + 3; int chartRowOffsetPixels = 0; int chartColumn = orderMonthFromIndex - 1; int chartColumnOffsetPixels = 20; chart.SetPosition(chartRow, chartRowOffsetPixels, chartColumn, chartColumnOffsetPixels); }
<c:dTable> <c:showKeys val="1"> </c:showKeys> </c:dTable>
// data table EnableChartDataTable(chart, true); public void EnableChartDataTable(ExcelChart chart, bool showLegendKeys) { var xdoc = chart.ChartXml; var nsm = new System.Xml.XmlNamespaceManager(xdoc.NameTable); // "http://schemas.openxmlformats.org/drawingml/2006/chart" var schemaChart = xdoc.DocumentElement.NamespaceURI; if (nsm.HasNamespace("c") == false) nsm.AddNamespace("c", schemaChart); var plotArea = xdoc.SelectSingleNode("/c:chartSpace/c:chart/c:plotArea", nsm); // <c:dTable> var dTable = plotArea.AppendElement(schemaChart, "c:dTable"); // <c:showKeys val="1"> var showKeys = dTable.AppendElement(schemaChart, "c:showKeys"); showKeys.AppendAttribute("val", (showLegendKeys ? "1" : "0")); }
// rows and columns indices int startRowIndex = 2; int territoryNameIndex = 2; int orderMonthFromIndex = 5; int totalIndex = 17; // group on territory group var territoryGroups = data.GroupBy(d => d.TerritoryGroup).OrderBy(g => g.Key); foreach (var territoryGroup in territoryGroups) { // new worksheet var ws = wb.Worksheets.Add(territoryGroup.Key); int rowIndex = startRowIndex; /* build the table up to the territory total rows */ // group on territory var territoryNameGroups = territoryGroup.GroupBy(d => d.TerritoryName).OrderBy(g => g.Key); int territoryNameFromRowIndex = rowIndex; foreach (var territoryNameGroup in territoryNameGroups) { /* add territory total row */ rowIndex++; } int toRowIndex = rowIndex - 1; int territoryNameToRowIndex = rowIndex - 1;
// chart ExcelPieChart chart = ws.Drawings.AddChart( "crtRevenues", eChartType.PieExploded3D ) as ExcelPieChart; // size chart.SetSize(700, 500); // title chart.Title.Text = "Revenues"; chart.Title.Font.Size = 18; chart.Title.Font.Bold = true; // delete legend chart.Legend.Remove();
// territories total revenues string serieAddress = ExcelCellBase.GetFullAddress( ws.Name, ExcelCellBase.GetAddress( territoryNameFromRowIndex, totalIndex, territoryNameToRowIndex, totalIndex ) ); // territory names string xSerieAddress = ExcelCellBase.GetFullAddress( ws.Name, ExcelCellBase.GetAddress( territoryNameFromRowIndex, territoryNameIndex, territoryNameToRowIndex, territoryNameIndex ) ); // add serie to chart ExcelPieChartSerie pieChartSerie = chart.Series.Add(serieAddress, xSerieAddress) as ExcelPieChartSerie; // serie appearance pieChartSerie.DataLabel.ShowCategory = true; pieChartSerie.DataLabel.ShowPercent = true; pieChartSerie.DataLabel.ShowLeaderLines = true; pieChartSerie.DataLabel.Position = eLabelPosition.OutEnd; pieChartSerie.Explosion = 10; // percent
// chart position int chartRow = toRowIndex + 30; int chartRowOffsetPixels = 0; int chartColumn = orderMonthFromIndex + 1; int chartColumnOffsetPixels = 30; chart.SetPosition(chartRow, chartRowOffsetPixels, chartColumn, chartColumnOffsetPixels); }
int EMU_PER_CM = 360000; int EMU_PER_INCH = 914400; int EMU_PER_PIXEL = 9525; int EMU_PER_POINT = 12700;
int ST_PERCENTAGE = 1000; // 1000th of a percent int ST_POSITIVE_FIXED_ANGLE = 60000; // 60000th of a degree
var ser = xdoc.SelectSingleNode( "/c:chartSpace/c:chart/c:plotArea/c:pie3DChart/c:ser[c:idx[@val='" + serieIndex + "']]", nsm );
<c:pie3DChart> <c:ser> <c:idx val="0" /> <c:spPr> <a:effectLst> <a:outerShdw> </a:outerShdw> </a:effectLst> </c:spPr> </c:ser> </c:pie3DChart>
<c:pie3DChart> <c:ser> <c:idx val="0" /> <c:spPr> <a:effectLst> <a:outerShdw sx="90000" sy="90000" blurRad="101600" dist="317500" dir="5400000"> </a:outerShdw> </a:effectLst> </c:spPr> </c:ser> </c:pie3DChart>
<c:pie3DChart> <c:ser> <c:idx val="0" /> <c:spPr> <a:effectLst> <a:outerShdw sx="90000" sy="90000" blurRad="101600" dist="317500" dir="5400000"> <a:srgbClr val="7F6000"> <a:alpha val="30%"> </a:alpha> </a:srgbClr> </a:outerShdw> </a:effectLst> </c:spPr> </c:ser> </c:pie3DChart>
// the index of the serie int serieIndex = 0; // Color int red = 127; int green = 96; int blue = 0; // Transparency int transparencyPer = 70; // Size int sizePer = 90; // Blur int blurPt = 8; // Angle int angleDgr = 90; // Distance int distancePt = 25; /*************************************************/ int EMU_PER_POINT = 12700; int ST_PERCENTAGE = 1000; int ST_POSITIVE_FIXED_ANGLE = 60000; /*************************************************/ var xdoc = chart.ChartXml; var nsm = new XmlNamespaceManager(xdoc.NameTable); // "http://schemas.openxmlformats.org/drawingml/2006/chart" var schemaChart = xdoc.DocumentElement.NamespaceURI; if (nsm.HasNamespace("c") == false) nsm.AddNamespace("c", schemaChart); var schemaDrawings = "http://schemas.openxmlformats.org/drawingml/2006/main"; if (nsm.HasNamespace("a") == false) nsm.AddNamespace("a", schemaDrawings); // <c:ser> var ser = xdoc.SelectSingleNode( "/c:chartSpace/c:chart/c:plotArea/c:pie3DChart/c:ser[c:idx[@val='" + serieIndex + "']]", nsm ); // <c:spPr> var spPr = ser.SelectSingleNode("./c:spPr", nsm); if (spPr == null) spPr = ser.AppendElement(schemaChart, "c:spPr"); // <a:effectLst> var effectLst = spPr.AppendElement(schemaDrawings, "a:effectLst"); // <a:outerShdw> var outerShdw = effectLst.AppendElement(schemaDrawings, "a:outerShdw"); // <a:outerShdw sx="90000" sy="90000"> outerShdw.AppendAttribute("sx", (sizePer * ST_PERCENTAGE).ToString()); outerShdw.AppendAttribute("sy", (sizePer * ST_PERCENTAGE).ToString()); // <a:outerShdw blurRad="101600"> outerShdw.AppendAttribute("blurRad", (blurPt * EMU_PER_POINT).ToString()); // <a:outerShdw dist="317500"> outerShdw.AppendAttribute("dist", (distancePt * EMU_PER_POINT).ToString()); // <a:outerShdw dir="5400000"> outerShdw.AppendAttribute("dir", (angleDgr * ST_POSITIVE_FIXED_ANGLE).ToString()); // <a:srgbClr val="7F6000"> var srgbClr = outerShdw.AppendElement(schemaDrawings, "a:srgbClr"); srgbClr.AppendAttribute("val", string.Format("{0:X2}{1:X2}{2:X2}", red, green, blue)); // <a:alpha val="30%"> var alpha = srgbClr.AppendElement(schemaDrawings, "a:alpha"); alpha.AppendAttribute("val", (100 - transparencyPer) + "%");
<c:pie3DChart> <c:ser> <c:idx val="0" /> <c:spPr> <a:sp3d prstMaterial="metal"> <a:bevelT w="127000" h="127000" /> <a:bevelB w="127000" h="127000" /> </a:sp3d> </c:spPr> </c:ser> </c:pie3DChart>
// the index of the serie int serieIndex = 0; // Material string material = "metal"; // Top bevel int topBevelWidthPt = 10; int topBevelHeightPt = 10; // Bottom bevel int bottomBevelWidthPt = 10; int bottomBevelHeightPt = 10; /*************************************************/ int EMU_PER_POINT = 12700; /*************************************************/ var xdoc = chart.ChartXml; var nsm = new XmlNamespaceManager(xdoc.NameTable); // "http://schemas.openxmlformats.org/drawingml/2006/chart" var schemaChart = xdoc.DocumentElement.NamespaceURI; if (nsm.HasNamespace("c") == false) nsm.AddNamespace("c", schemaChart); var schemaDrawings = "http://schemas.openxmlformats.org/drawingml/2006/main"; if (nsm.HasNamespace("a") == false) nsm.AddNamespace("a", schemaDrawings); // <c:ser> var ser = xdoc.SelectSingleNode( "/c:chartSpace/c:chart/c:plotArea/c:pie3DChart/c:ser[c:idx[@val='" + serieIndex + "']]", nsm ); // <c:spPr> var spPr = ser.SelectSingleNode("./c:spPr", nsm); if (spPr == null) spPr = ser.AppendElement(schemaChart, "c:spPr"); // <a:sp3d prstMaterial="metal"> var sp3d = spPr.AppendElement(schemaDrawings, "a:sp3d"); sp3d.AppendAttribute("prstMaterial", material); // <a:bevelT w="127000" h="127000" /> var bevelT = sp3d.AppendElement(schemaDrawings, "a:bevelT"); bevelT.AppendAttribute("w", (topBevelWidthPt * EMU_PER_POINT).ToString()); bevelT.AppendAttribute("h", (topBevelHeightPt * EMU_PER_POINT).ToString()); // <a:bevelB w="127000" h="127000" /> var bevelB = sp3d.AppendElement(schemaDrawings, "a:bevelB"); bevelB.AppendAttribute("w", (bottomBevelWidthPt * EMU_PER_POINT).ToString()); bevelB.AppendAttribute("h", (bottomBevelHeightPt * EMU_PER_POINT).ToString());
// POCOs ExcelRangeBase.LoadFromCollection<T>(IEnumerable<T> Collection) // DataTable ExcelRangeBase.LoadFromDataTable(DataTable Table) // text file ExcelRangeBase.LoadFromText(FileInfo TextFile) // objects ExcelRangeBase.LoadFromArrays(IEnumerable<object[]> Data)
IEnumerable<DataRow> data; bool printHeaders = true; var tableStyle = OfficeOpenXml.Table.TableStyles.Medium2; using (ExcelRangeBase range = ws.Cells[2, 2] .LoadFromCollection<DataRow>(data, printHeaders, tableStyle)) { } // data table OfficeOpenXml.Table.ExcelTable tblData = ws.Tables[ws.Tables.Count - 1]; tblData.Name = "tblData";
// rows and columns indices int startRowIndex = 2; int territoryGroupIndex = 2; int territoryNameIndex = 3; int salesPersonIndex = 4; int orderDateIndex = 5; int productCategoryIndex = 6; int productSubcategoryIndex = 7; int productIndex = 8; int orderQtyIndex = 9; int unitPriceDiscountIndex = 10; int discountIndex = 11; int unitPriceIndex = 12; int lineTotalIndex = 13; int orderYearIndex = 14; int orderMonthIndex = 15; IEnumerable<DataRow> data; bool printHeaders = true; var tableStyle = OfficeOpenXml.Table.TableStyles.Medium2; using (ExcelRangeBase range = ws.Cells[startRowIndex, territoryGroupIndex] .LoadFromCollection<DataRow>(data, printHeaders, tableStyle)) { // border style range.Style.Border.Top.Style = ExcelBorderStyle.Thin; range.Style.Border.Bottom.Style = ExcelBorderStyle.Thin; range.Style.Border.Left.Style = ExcelBorderStyle.Thin; range.Style.Border.Right.Style = ExcelBorderStyle.Thin; // border color range.Style.Border.Top.Color.SetColor(System.Drawing.Color.LightGray); range.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.LightGray); range.Style.Border.Left.Color.SetColor(System.Drawing.Color.LightGray); range.Style.Border.Right.Color.SetColor(System.Drawing.Color.LightGray); } // data table OfficeOpenXml.Table.ExcelTable tblData = ws.Tables[ws.Tables.Count - 1]; tblData.Name = "tblData"; // headers ws.Cells[startRowIndex, territoryGroupIndex].Value = "Territory Group"; ws.Cells[startRowIndex, territoryNameIndex].Value = "Territory"; ws.Cells[startRowIndex, salesPersonIndex].Value = "Salesperson"; ws.Cells[startRowIndex, orderDateIndex].Value = "Order Date"; ws.Cells[startRowIndex, productCategoryIndex].Value = "Product Category"; ws.Cells[startRowIndex, productSubcategoryIndex].Value = "Product Subcategory"; ws.Cells[startRowIndex, productIndex].Value = "Product"; ws.Cells[startRowIndex, orderQtyIndex].Value = "Quantity"; ws.Cells[startRowIndex, unitPriceDiscountIndex].Value = "Unit Price Discount"; ws.Cells[startRowIndex, discountIndex].Value = "Discount"; ws.Cells[startRowIndex, unitPriceIndex].Value = "Unit Price"; ws.Cells[startRowIndex, lineTotalIndex].Value = "Revenue"; ws.Cells[startRowIndex, orderYearIndex].Value = "Order Year"; ws.Cells[startRowIndex, orderMonthIndex].Value = "Order Month"; // headers style using (var cells = ws.Cells[startRowIndex, territoryGroupIndex, startRowIndex, orderMonthIndex]) { cells.Style.Font.Bold = true; cells.Style.Font.Size = 11; cells.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; }
// data cells ExcelWorksheets wsData = ep.Workbook.Worksheets["Data"]; ExcelTable tblData = wsData.Tables["tblData"]; ExcelRange dataCells = wsData.Cells[tblData.Address.Address];
// pivot table ExcelRange pvtLocation = ws.Cells["B4"]; string pvtName = "pvtSalesBySalesperson"; ExcelPivotTable pivotTable = ws.PivotTables.Add(pvtLocation, dataCells, pvtName); // headers pivotTable.ShowHeaders = true; pivotTable.RowHeaderCaption = "Salesperson"; // grand total pivotTable.ColumGrandTotals = true; pivotTable.GrandTotalCaption = "Total"; // data fields are placed in columns pivotTable.DataOnRows = false; // style pivotTable.TableStyle = OfficeOpenXml.Table.TableStyles.Medium9;
// filters: Territory Group ExcelPivotTableField territoryGroupPageField = pivotTable.PageFields.Add( pivotTable.Fields["Territory Group"] ); territoryGroupPageField.Sort = eSortType.Ascending; // rows: Salesperson ExcelPivotTableField salesPersonRowField = pivotTable.RowFields.Add( pivotTable.Fields["Salesperson"] ); // values: Revenue ExcelPivotTableDataField revenueDataField = pivotTable.DataFields.Add( pivotTable.Fields["Revenue"] ); revenueDataField.Function = DataFieldFunctions.Sum; revenueDataField.Format = "#,##0_);(#,##0)"; revenueDataField.Name = "Revenue";
ExcelPivotTableField field = salesPersonRowField; var pivotField = xdoc.SelectSingleNode( "/x:pivotTableDefinition/x:pivotFields/x:pivotField[position()=" + (field.Index + 1) + "]", nsm );
<x:pivotField sortType="descending"> <x:autoSortScope> <x:pivotArea> <x:references count="1"> <x:reference field="4294967294"> <x:x v="0" /> </x:reference> </x:references> </x:pivotArea> </x:autoSortScope> </x:pivotField>
ExcelPivotTableField field = salesPersonRowField; ExcelPivotTableDataField dataField = revenueDataField; bool descending = true; /*************************************************/ var xdoc = pivotTable.PivotTableXml; var nsm = new XmlNamespaceManager(xdoc.NameTable); // "http://schemas.openxmlformats.org/spreadsheetml/2006/main" var schemaMain = xdoc.DocumentElement.NamespaceURI; if (nsm.HasNamespace("x") == false) nsm.AddNamespace("x", schemaMain); // <x:pivotField sortType="descending"> var pivotField = xdoc.SelectSingleNode( "/x:pivotTableDefinition/x:pivotFields/x:pivotField[position()=" + (field.Index + 1) + "]", nsm ); pivotField.AppendAttribute("sortType", (descending ? "descending" : "ascending")); // <x:autoSortScope> var autoSortScope = pivotField.AppendElement(schemaMain, "x:autoSortScope"); // <x:pivotArea> var pivotArea = autoSortScope.AppendElement(schemaMain, "x:pivotArea"); // <x:references count="1"> var references = pivotArea.AppendElement(schemaMain, "x:references"); references.AppendAttribute("count", "1"); // <x:reference field="4294967294"> var reference = references.AppendElement(schemaMain, "x:reference"); // Specifies the index of the field to which this filter refers. // A value of -2 indicates the 'data' field. // int -> uint: -2 -> ((2^32)-2) = 4294967294 reference.AppendAttribute("field", "4294967294"); // <x:x v="0"> var x = reference.AppendElement(schemaMain, "x:x"); int v = 0; foreach (ExcelPivotTableDataField pivotDataField in pivotTable.DataFields) { if (pivotDataField == dataField) { x.AppendAttribute("v", v.ToString()); break; } v++; }
ExcelBarChart chart = ws.Drawings.AddChart( "crtSalesBySalesperson", eChartType.BarClustered, pivotTable ) as ExcelBarChart; chart.SetPosition(1, 0, 4, 0); chart.SetSize(600, 400); chart.Title.Text = "Sales by Salesperson"; chart.Title.Font.Size = 18; chart.Title.Font.Bold = true; chart.GapWidth = 25; chart.DataLabel.ShowValue = true; chart.Legend.Remove(); chart.XAxis.MajorTickMark = eAxisTickMark.None; chart.XAxis.MinorTickMark = eAxisTickMark.None; chart.YAxis.DisplayUnit = 1000; // K chart.YAxis.Deleted = true; ExcelBarChartSerie serie = chart.Series[0] as ExcelBarChartSerie; serie.Fill.Color = System.Drawing.Color.FromArgb(91, 155, 213);
bool isXAxis = true; bool isMajorGridlines = true; bool enable = false; /*************************************************/ var xdoc = chart.ChartXml; var nsm = new XmlNamespaceManager(xdoc.NameTable); // "http://schemas.openxmlformats.org/drawingml/2006/chart" var schemaChart = xdoc.DocumentElement.NamespaceURI; if (nsm.HasNamespace("c") == false) nsm.AddNamespace("c", schemaChart); var axes = xdoc.SelectNodes( string.Format("/c:chartSpace/c:chart/c:plotArea/{0}", (isXAxis ? "c:valAx" : "c:catAx")), nsm ); if (axes != null && axes.Count > 0) { foreach (XmlNode axis in axes) { var gridlines = axis.SelectSingleNode( (isMajorGridlines ? "c:majorGridlines" : "c:minorGridlines"), nsm ); if (gridlines != null) { if (enable) { if (gridlines == null) { axis.AppendElement( schemaChart, (isMajorGridlines ? "c:majorGridlines" : "c:minorGridlines") ); } } else { if (gridlines != null) axis.RemoveChild(gridlines); } } } }
<c:catAx> <c:scaling> <c:orientation val="maxMin"> </c:orientation> </c:scaling> </c:catAx>
bool maxMin = true; /*************************************************/ var xdoc = chart.ChartXml; var nsm = new XmlNamespaceManager(xdoc.NameTable); // "http://schemas.openxmlformats.org/drawingml/2006/chart" var schemaChart = xdoc.DocumentElement.NamespaceURI; if (nsm.HasNamespace("c") == false) nsm.AddNamespace("c", schemaChart); // <c:catAx> var catAxs = xdoc.SelectNodes("/c:chartSpace/c:chart/c:plotArea/c:catAx", nsm); if (catAxs != null && catAxs.Count > 0) { foreach (XmlNode catAx in catAxs) { // <c:scaling> var scaling = catAx.AppendElement(schemaChart, "c:scaling"); // <c:orientation val="maxMin"> var orientation = scaling.AppendElement(schemaChart, "c:orientation"); orientation.AppendAttribute("val", (maxMin ? "maxMin" : "minMax")); } }
// data cells ExcelWorksheets wsData = ep.Workbook.Worksheets["Data"]; ExcelTable tblData = wsData.Tables["tblData"]; ExcelRange dataCells = wsData.Cells[tblData.Address.Address]; // pivot table ExcelRange pvtLocation = ws.Cells["B4"]; string pvtName = "pvtSalesByProductSubcategory"; ExcelPivotTable pivotTable = ws.PivotTables.Add(pvtLocation, dataCells, pvtName); // headers pivotTable.ShowHeaders = true; pivotTable.RowHeaderCaption = "Subcategory"; // grand total pivotTable.ColumGrandTotals = true; pivotTable.GrandTotalCaption = "Total"; // data fields are placed in columns pivotTable.DataOnRows = false; // style pivotTable.TableStyle = OfficeOpenXml.Table.TableStyles.Medium14; // filters: Territory Group ExcelPivotTableField territoryGroupPageField = pivotTable.PageFields.Add( pivotTable.Fields["Territory Group"] ); territoryGroupPageField.Sort = eSortType.Ascending; // rows: Product Subcategory ExcelPivotTableField productSubcategoryRowField = pivotTable.RowFields.Add( pivotTable.Fields["Product Subcategory"] ); // values: Revenue ExcelPivotTableDataField revenueDataField = pivotTable.DataFields.Add( pivotTable.Fields["Revenue"] ); revenueDataField.Function = DataFieldFunctions.Sum; revenueDataField.Format = "#,##0_);(#,##0)"; revenueDataField.Name = "Revenue"; // sort on revenues ExcelPivotTableField field = productSubcategoryRowField; ExcelPivotTableDataField dataField = revenueDataField; bool descending = true; pivotTable.SortOnDataField(field, dataField, descending);
<x:filters count="1"> <x:filter id="1" type="count" fld="5" iMeasureFld="0"> </x:filter> </x:filters>
<x:filters count="1"> <x:filter id="1" type="count" fld="5" iMeasureFld="0"> <x:autoFilter> <x:filterColumn colId="0"> <x:top10 val="5" top="1" percent="0"> </x:top10> </x:filterColumn> </x:autoFilter> </x:filter> </x:filters>
ExcelPivotTableField field = productSubcategoryRowField; ExcelPivotTableDataField dataField = revenueDataField; int number = 5; bool bottom = false; bool percent = false; /*************************************************/ var xdoc = pivotTable.PivotTableXml; var nsm = new XmlNamespaceManager(xdoc.NameTable); // "http://schemas.openxmlformats.org/spreadsheetml/2006/main" var schemaMain = xdoc.DocumentElement.NamespaceURI; if (nsm.HasNamespace("x") == false) nsm.AddNamespace("x", schemaMain); // <x:filters> var filters = xdoc.SelectSingleNode("/x:pivotTableDefinition/x:filters", nsm); int filtersCount = 0; if (filters == null) { var pivotTableDefinition = xdoc.SelectSingleNode("/x:pivotTableDefinition", nsm); filters = pivotTableDefinition.AppendElement(schemaMain, "x:filters"); filtersCount = 1; } else { XmlAttribute countAttr = filters.Attributes["count"]; int count = int.Parse(countAttr.Value); filtersCount = count + 1; } // <x:filters count="1"> filters.AppendAttribute("count", filtersCount.ToString()); // <x:filter id="1" type="count"> var filter = filters.AppendElement(schemaMain, "x:filter"); filter.AppendAttribute("id", filtersCount.ToString()); filter.AppendAttribute("type", (percent ? "percent" : "count")); // <x:filter fld="5"> int fld = 0; foreach (ExcelPivotTableField pivotField in pivotTable.Fields) { if (pivotField == field) { filter.AppendAttribute("fld", fld.ToString()); break; } fld++; } // <x:filter iMeasureFld="0"> int iMeasureFld = 0; foreach (ExcelPivotTableDataField pivotDataField in pivotTable.DataFields) { if (pivotDataField == dataField) { filter.AppendAttribute("iMeasureFld", iMeasureFld.ToString()); break; } iMeasureFld++; } // <x:autoFilter> var autoFilter = filter.AppendElement(schemaMain, "x:autoFilter"); // <x:filterColumn colId="0"> var filterColumn = autoFilter.AppendElement(schemaMain, "x:filterColumn"); filterColumn.AppendAttribute("colId", "0"); // the first auto filter in the pivot table // <x:top10 val="5" top="1" percent="0"> var top10 = filterColumn.AppendElement(schemaMain, "x:top10"); top10.AppendAttribute("val", number.ToString()); top10.AppendAttribute("top", (bottom ? "0" : "1")); top10.AppendAttribute("percent", (percent ? "1" : "0"));
// data cells ExcelWorksheets wsData = ep.Workbook.Worksheets["Data"]; ExcelTable tblData = wsData.Tables["tblData"]; ExcelRange dataCells = wsData.Cells[tblData.Address.Address]; // pivot table ExcelRange pvtLocation = ws.Cells["B4"]; string pvtName = "pvtOrders"; ExcelPivotTable pivotTable = ws.PivotTables.Add(pvtLocation, dataCells, pvtName); // headers pivotTable.ShowHeaders = true; pivotTable.RowHeaderCaption = "Subcategory"; // grand total pivotTable.ColumGrandTotals = true; pivotTable.GrandTotalCaption = "Total"; // data fields are placed in columns pivotTable.DataOnRows = false; // style pivotTable.TableStyle = OfficeOpenXml.Table.TableStyles.Medium10; // filters: Territory Group ExcelPivotTableField territoryGroupPageField = pivotTable.PageFields.Add( pivotTable.Fields["Territory Group"] ); territoryGroupPageField.Sort = eSortType.Ascending; // rows: Product Subcategory ExcelPivotTableField productSubcategoryRowField = pivotTable.RowFields.Add( pivotTable.Fields["Product Subcategory"] ); // values: Revenue ExcelPivotTableDataField revenueDataField = pivotTable.DataFields.Add( pivotTable.Fields["Revenue"] ); revenueDataField.Function = DataFieldFunctions.Sum; revenueDataField.Format = "#,##0_);(#,##0)"; revenueDataField.Name = "Revenue";
// values: Unit Price ExcelPivotTableDataField unitPriceDataField = pivotTable.DataFields.Add( pivotTable.Fields["Unit Price"] ); unitPriceDataField.Function = DataFieldFunctions.Average; unitPriceDataField.Format = "#,##0_);(#,##0)"; unitPriceDataField.Name = "Unit Price";
// values: Quantity ExcelPivotTableDataField quantityDataField = pivotTable.DataFields.Add( pivotTable.Fields["Quantity"] ); quantityDataField.Function = DataFieldFunctions.Sum; quantityDataField.Format = "#,##0_);(#,##0)"; quantityDataField.Name = "Quantity";
// values: # Orders: Quantity Count ExcelPivotTableDataField ordersCountDataField = pivotTable.DataFields.Add( pivotTable.Fields["Quantity"] ); ordersCountDataField.Function = DataFieldFunctions.Count; ordersCountDataField.Format = "#,##0_);(#,##0)"; ordersCountDataField.Name = "# Orders";
// sort on # orders ExcelPivotTableField field = productSubcategoryRowField; ExcelPivotTableDataField dataField = ordersCountDataField; bool descending = true; pivotTable.SortOnDataField(field, dataField, descending);
// data cells ExcelWorksheets wsData = ep.Workbook.Worksheets["Data"]; ExcelTable tblData = wsData.Tables["tblData"]; ExcelRange dataCells = wsData.Cells[tblData.Address.Address]; // pivot table ExcelRange pvtLocation = ws.Cells["B4"]; string pvtName = "pvtRevenuePercentage"; ExcelPivotTable pivotTable = ws.PivotTables.Add(pvtLocation, dataCells, pvtName); // headers pivotTable.ShowHeaders = true; pivotTable.RowHeaderCaption = "Subcategory"; // grand total pivotTable.ColumGrandTotals = true; pivotTable.GrandTotalCaption = "Total"; // data fields are placed in columns pivotTable.DataOnRows = false; // style pivotTable.TableStyle = OfficeOpenXml.Table.TableStyles.Medium11; // filters: Territory Group ExcelPivotTableField territoryGroupPageField = pivotTable.PageFields.Add( pivotTable.Fields["Territory Group"] ); territoryGroupPageField.Sort = eSortType.Ascending; // rows: Product Subcategory ExcelPivotTableField productSubcategoryRowField = pivotTable.RowFields.Add( pivotTable.Fields["Product Subcategory"] ); // rows: Salesperson ExcelPivotTableField salesPersonRowField = pivotTable.RowFields.Add( pivotTable.Fields["Salesperson"] ); // values: Revenue ExcelPivotTableDataField revenueDataField = pivotTable.DataFields.Add( pivotTable.Fields["Revenue"] ); revenueDataField.Function = DataFieldFunctions.Sum; revenueDataField.Format = "#,##0_);(#,##0)"; revenueDataField.Name = "Revenue"; // sort product subcategory on revenue, descending pivotTable.SortOnDataField(productSubcategoryRowField, revenueDataField, true); // sort salesperson on revenue, ascending pivotTable.SortOnDataField(salesPersonRowField, revenueDataField, false);
// values: % Revenue ExcelPivotTableDataField revenuePercentageDataField = pivotTable.DataFields.Add( pivotTable.Fields["Revenue"] ); revenuePercentageDataField.Function = DataFieldFunctions.Sum; revenuePercentageDataField.Format = "0.00%"; revenuePercentageDataField.Name = "% Revenue";
<x:pivotTableDefinition> <x:dataFields> <x:dataField name="% Revenue" showDataAs="percentOfTotal"> </x:dataField> </x:dataFields> </x:pivotTableDefinition>
// show % Revenue as percentage of revenue grand total ExcelPivotTableDataField dataField = revenuePercentageDataField; string showDataAs = "percentOfTotal"; /*************************************************/ var xdoc = pivotTable.PivotTableXml; var nsm = new XmlNamespaceManager(xdoc.NameTable); // "http://schemas.openxmlformats.org/spreadsheetml/2006/main" var schemaMain = xdoc.DocumentElement.NamespaceURI; if (nsm.HasNamespace("x") == false) nsm.AddNamespace("x", schemaMain); // <x:dataField name="% Revenue"> var dataFieldNode = xdoc.SelectSingleNode( "/x:pivotTableDefinition/x:dataFields/x:dataField[@name='" + dataField.Name + "']", nsm ); // <x:dataField showDataAs="percentOfTotal"> dataFieldNode.AppendAttribute("showDataAs", showDataAs);
// values: % Parent ExcelPivotTableDataField parentRowPercentageDataField = pivotTable.DataFields.Add( pivotTable.Fields["Revenue"] ); parentRowPercentageDataField.Function = DataFieldFunctions.Sum; parentRowPercentageDataField.Format = "0.00%"; parentRowPercentageDataField.Name = "% Parent";
<x:pivotTableDefinition updatedVersion="5"> <x:dataFields> <x:dataField name="% Parent"> <x:extLst> <x:ext uri="{E15A36E0-9728-4e99-A89B-3F7291B0FE68}"> <x14:dataField pivotShowAs="percentOfParentRow"> </x14:dataField> </x:ext> </x:extLst> </x:dataField> </x:dataFields> </x:pivotTableDefinition>
// show % Parent as percentage of parent row (= product subcategory revenue) ExcelPivotTableDataField dataField = parentRowPercentageDataField; string pivotShowAs = "percentOfParentRow"; /*************************************************/ var xdoc = pivotTable.PivotTableXml; var nsm = new XmlNamespaceManager(xdoc.NameTable); // "http://schemas.openxmlformats.org/spreadsheetml/2006/main" var schemaMain = xdoc.DocumentElement.NamespaceURI; if (nsm.HasNamespace("x") == false) nsm.AddNamespace("x", schemaMain); var schemaMainX14 = "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"; if (nsm.HasNamespace("x14") == false) nsm.AddNamespace("x14", schemaMainX14); // <x:pivotTableDefinition updatedVersion="5"> var pivotTableDefinition = xdoc.SelectSingleNode("/x:pivotTableDefinition", nsm); pivotTableDefinition.AppendAttribute("updatedVersion", "5"); // <x:dataField name="% Parent"> var dataFieldNode = xdoc.SelectSingleNode( "/x:pivotTableDefinition/x:dataFields/x:dataField[@name='" + dataField.Name + "']", nsm ); // <x:extLst> var extLst = dataFieldNode.AppendElement(schemaMain, "x:extLst"); // <x:ext uri="{E15A36E0-9728-4e99-A89B-3F7291B0FE68}"> var ext = extLst.AppendElement(schemaMain, "x:ext"); ext.AppendAttribute("uri", "{E15A36E0-9728-4e99-A89B-3F7291B0FE68}"); // <x14:dataField pivotShowAs="percentOfParentRow"> var x14DataField = ext.AppendElement(schemaMainX14, "x14:dataField"); x14DataField.AppendAttribute("pivotShowAs", pivotShowAs);
// values: % Subcategory ExcelPivotTableDataField subcategoryPercentageDataField = pivotTable.DataFields.Add( pivotTable.Fields["Revenue"] ); subcategoryPercentageDataField.Function = DataFieldFunctions.Sum; subcategoryPercentageDataField.Format = "0.00%"; subcategoryPercentageDataField.Name = "% Subcategory";
ExcelPivotTableField baseField = pivotTable.Fields["Product Subcategory"]; int index = baseField.Index; // 5
<x:pivotTableDefinition updatedVersion="5"> <x:dataFields> <x:dataField name="% Subcategory" baseField="5"> <x:extLst> <x:ext uri="{E15A36E0-9728-4e99-A89B-3F7291B0FE68}"> <x14:dataField pivotShowAs="percentOfParent"> </x14:dataField> </x:ext> </x:extLst> </x:dataField> </x:dataFields> </x:pivotTableDefinition>
// show % Subcategory as percentage of product subcategory revenue ExcelPivotTableDataField dataField = subcategoryPercentageDataField; string pivotShowAs = "percentOfParent"; ExcelPivotTableField baseField = pivotTable.Fields["Product Subcategory"]; /*************************************************/ var xdoc = pivotTable.PivotTableXml; var nsm = new XmlNamespaceManager(xdoc.NameTable); // "http://schemas.openxmlformats.org/spreadsheetml/2006/main" var schemaMain = xdoc.DocumentElement.NamespaceURI; if (nsm.HasNamespace("x") == false) nsm.AddNamespace("x", schemaMain); var schemaMainX14 = "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"; if (nsm.HasNamespace("x14") == false) nsm.AddNamespace("x14", schemaMainX14); // <x:pivotTableDefinition updatedVersion="5"> var pivotTableDefinition = xdoc.SelectSingleNode("/x:pivotTableDefinition", nsm); pivotTableDefinition.AppendAttribute("updatedVersion", "5"); // <x:dataField name="% Subcategory"> var dataFieldNode = xdoc.SelectSingleNode( "/x:pivotTableDefinition/x:dataFields/x:dataField[@name='" + dataField.Name + "']", nsm ); // <x:dataField baseField="5"> dataFieldNode.AppendAttribute("baseField", baseField.Index.ToString()); // <x:extLst> var extLst = dataFieldNode.AppendElement(schemaMain, "x:extLst"); // <x:ext uri="{E15A36E0-9728-4e99-A89B-3F7291B0FE68}"> var ext = extLst.AppendElement(schemaMain, "x:ext"); ext.AppendAttribute("uri", "{E15A36E0-9728-4e99-A89B-3F7291B0FE68}"); // <x14:dataField pivotShowAs="percentOfParentRow"> var x14DataField = ext.AppendElement(schemaMainX14, "x14:dataField"); x14DataField.AppendAttribute("pivotShowAs", pivotShowAs);
// data cells ExcelWorksheets wsData = ep.Workbook.Worksheets["Data"]; ExcelTable tblData = wsData.Tables["tblData"]; ExcelRange dataCells = wsData.Cells[tblData.Address.Address]; // pivot table ExcelRange pvtLocation = ws.Cells["B4"]; string pvtName = "pvtMonthlySales"; ExcelPivotTable pivotTable = ws.PivotTables.Add(pvtLocation, dataCells, pvtName); // headers pivotTable.ShowHeaders = false; // grand total pivotTable.ColumGrandTotals = true; pivotTable.GrandTotalCaption = "Total"; // data fields are placed in columns pivotTable.DataOnRows = false; // style pivotTable.TableStyle = OfficeOpenXml.Table.TableStyles.Medium6; // filters: Territory Group ExcelPivotTableField territoryGroupPageField = pivotTable.PageFields.Add( pivotTable.Fields["Territory Group"] ); territoryGroupPageField.Sort = eSortType.Ascending; // rows: Salesperson ExcelPivotTableField salesPersonRowField = pivotTable.RowFields.Add( pivotTable.Fields["Salesperson"] ); salesPersonRowField.Sort = eSortType.Ascending; // rows: Year ExcelPivotTableField yearRowField = pivotTable.RowFields.Add( pivotTable.Fields["Order Year"] ); yearRowField.Sort = eSortType.Descending; yearRowField.Name = "Year"; // values: Revenue ExcelPivotTableDataField revenueDataField = pivotTable.DataFields.Add( pivotTable.Fields["Revenue"] ); revenueDataField.Function = DataFieldFunctions.Sum; revenueDataField.Format = "#,##0_);(#,##0)"; revenueDataField.Name = "Revenue";
monthColumnField.AddDateGrouping(eDateGroupBy.Months);
// columns: Month ExcelPivotTableField monthColumnField = pivotTable.ColumnFields.Add( pivotTable.Fields["Order Date"] ); monthColumnField.AddDateGrouping(eDateGroupBy.Months); monthColumnField.Sort = eSortType.Ascending; monthColumnField.Name = "Month"; var enUS = System.Globalization.CultureInfo.CreateSpecificCulture("en-US"); monthColumnField.Items[0].Text = "<"; // below min date. not in use. for (int month = 1; month <= 12; month++) monthColumnField.Items[month].Text = enUS.DateTimeFormat.GetAbbreviatedMonthName(month); monthColumnField.Items[13].Text = ">"; // above max date. not in use.
// data cells ExcelWorksheets wsData = ep.Workbook.Worksheets["Data"]; ExcelTable tblData = wsData.Tables["tblData"]; ExcelRange dataCells = wsData.Cells[tblData.Address.Address]; // pivot table ExcelRange pvtLocation = ws.Cells["B4"]; string pvtName = "pvtQuarterlySales"; ExcelPivotTable pivotTable = ws.PivotTables.Add(pvtLocation, dataCells, pvtName); // headers pivotTable.ShowHeaders = false; // grand total pivotTable.ColumGrandTotals = true; pivotTable.GrandTotalCaption = "Total"; // data fields are placed in columns pivotTable.DataOnRows = false; // style pivotTable.TableStyle = OfficeOpenXml.Table.TableStyles.Medium1; // filters: Territory Group ExcelPivotTableField territoryGroupPageField = pivotTable.PageFields.Add( pivotTable.Fields["Territory Group"] ); territoryGroupPageField.Sort = eSortType.Ascending; // rows: Salesperson ExcelPivotTableField salesPersonRowField = pivotTable.RowFields.Add( pivotTable.Fields["Salesperson"] ); salesPersonRowField.Sort = eSortType.Ascending; // values: Revenue ExcelPivotTableDataField revenueDataField = pivotTable.DataFields.Add( pivotTable.Fields["Revenue"] ); revenueDataField.Function = DataFieldFunctions.Sum; revenueDataField.Format = "#,##0_);(#,##0)"; revenueDataField.Name = "Revenue";
ExcelPivotTableField quarterColumnField = pivotTable.ColumnFields.Add( pivotTable.Fields["Order Date"] ); quarterColumnField.AddDateGrouping(eDateGroupBy.Years | eDateGroupBy.Quarters);
ExcelPivotTableField yearColumnField = pivotTable.Fields.GetDateGroupField(eDateGroupBy.Years);
bool areSame = (quarterColumnField == pivotTable.Fields.GetDateGroupField(eDateGroupBy.Quarters));
// columns: Year, Quarter ExcelPivotTableField quarterColumnField = pivotTable.ColumnFields.Add( pivotTable.Fields["Order Date"] ); quarterColumnField.AddDateGrouping(eDateGroupBy.Years | eDateGroupBy.Quarters); quarterColumnField.Sort = eSortType.Descending; quarterColumnField.Name = "Quarter"; ExcelPivotTableField yearColumnField = pivotTable.Fields.GetDateGroupField(eDateGroupBy.Years); yearColumnField.Sort = eSortType.Descending; yearColumnField.Name = "Year"; quarterColumnField.Items[0].Text = "<"; // below min date. not in use. for (int quarter = 1; quarter <= 4; quarter++) quarterColumnField.Items[quarter].Text = "Q" + quarter; quarterColumnField.Items[5].Text = ">"; // above max date. not in use.
using (var ms = new MemoryStream()) { // original excel using (var ep = new ExcelPackage(ms)) { var wb = ep.Workbook; var ws = wb.Worksheets.Add("Original"); ws.Cells[1, 1].Value = "Value from original workbook"; ws.Column(1).AutoFit(); // original excel is written into ep.Stream // ep.Stream is the same MemoryStream as ms ep.Save(); // you can't edit ExcelPackage after it was finalized (Save, SaveAs, GetAsByteArray) } // excel copy 1 using (var ep = new ExcelPackage()) { ep.Load(ms); var wb = ep.Workbook; var ws = wb.Worksheets[1]; ws.Name = "Copy 1"; ws.Cells[2, 1].Value = "Copy 1"; using (var file = System.IO.File.OpenWrite("Copy 1.xlsx")) { ep.SaveAs(file); } } // excel copy 2 using (var ep = new ExcelPackage()) { ep.Load(ms); var wb = ep.Workbook; var ws = wb.Worksheets[1]; ws.Name = "Copy 2"; ws.Cells[2, 1].Value = "Copy 2"; using (var file = System.IO.File.OpenWrite("Copy 2.xlsx")) { ep.SaveAs(file); } } }
// original excel byte[] excel = null; using (var ep = new ExcelPackage()) { var wb = ep.Workbook; var ws = wb.Worksheets.Add("Original"); ws.Cells[1, 1].Value = "Value from original workbook"; ws.Column(1).AutoFit(); excel = ep.GetAsByteArray(); } // excel copy 1 using (var ep = new ExcelPackage()) { using (var ms = new MemoryStream(excel)) { ep.Load(ms); } var wb = ep.Workbook; var ws = wb.Worksheets[1]; ws.Name = "Copy 1"; ws.Cells[2, 1].Value = "Copy 1"; using (var file = System.IO.File.OpenWrite("Copy 1.xlsx")) { ep.SaveAs(file); } } // excel copy 2 using (var ep = new ExcelPackage()) { using (var ms = new MemoryStream(excel)) { ep.Load(ms); } var wb = ep.Workbook; var ws = wb.Worksheets[1]; ws.Name = "Copy 2"; ws.Cells[2, 1].Value = "Copy 2"; using (var file = System.IO.File.OpenWrite("Copy 2.xlsx")) { ep.SaveAs(file); } }
PM> Install-Package DotNetZip -Version 1.10.1
byte[] excel; // from EPPlus, from file byte[] excelNew = null; using (var zipStream = new MemoryStream(excel)) { using (Ionic.Zip.ZipFile zipFile = Ionic.Zip.ZipFile.Read(zipStream)) { // change zip file // zipFile.AddEntry(); // zipFile.RemoveEntry(); using (var outStream = new MemoryStream()) { zipFile.Save(outStream); excelNew = outStream.ToArray(); } } } // save new excel System.IO.File.WriteAllBytes(@"C:\excelNew.xlsx", excelNew);
byte[] excel; // from EPPlus, from file string outputFolder = @"C:\"; using (var zipStream = new MemoryStream(excel)) { using (Ionic.Zip.ZipFile zipFile = Ionic.Zip.ZipFile.Read(zipStream)) { // assumption that all the files are XMLs // not testing for other resources such as images foreach (Ionic.Zip.ZipEntry zipEntry in zipFile) { XmlDocument xdoc = new XmlDocument(); using (var ms = new MemoryStream()) { // extract to memory zipEntry.Extract(ms); // load XmlDocument ms.Position = 0; xdoc.Load(ms); } // output path string outputPath = Path.GetFullPath( Path.Combine(outputFolder, zipEntry.FileName) ); // create output directory string directory = Path.GetDirectoryName(outputPath); if (Directory.Exists(directory) == false) Directory.CreateDirectory(directory); // write xml to file, tab indentation, UTF-8 encoding using (var writer = new System.Xml.XmlTextWriter(outputPath, System.Text.Encoding.UTF8)) { writer.Formatting = Formatting.Indented; writer.Indentation = 1; writer.IndentChar = '\t'; xdoc.Save(writer); } } } }
byte[] excel; // from EPPlus, from file string excelFileName = "MyExcel.xlsx"; string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; string contentDisposition = string.Format("attachment; filename=\"{0}\"", System.Uri.EscapeDataString(excelFileName) ); System.Web.HttpResponse response = Page.Response; response.ContentEncoding = System.Text.Encoding.Unicode; response.ContentType = contentType; response.AddHeader("content-disposition", contentDisposition); response.BinaryWrite(excel); response.Flush(); response.End();