Generate excel chart from smart marker aspose - excel

I have an excel template with following two columns period and points, trend.period and trend.points are aspose smart marker that represent the data.
Period Points
&=trend.period &=trend.points
The table generated is below.
Period Points
4Q'14 27
1Q'15 0
2Q'15 0
3Q'15 0
4Q'15 200
It's easy to generate column chart for table 2, how to generate the same chart for table 1 with smart marker?

You may accomplish the task using Aspose.Cells' Smart Markers feature. All you need to do is create Named ranges based on your Smart Markers inserted into the cells. I have written a sample code using Aspose.Cells APIs for your requirements. Please refer to it and you may add/update the code segment accordingly for your needs.
e.g
Sample code:
DataTable dt = new DataTable("Trend");
dt.Columns.Add("Period", typeof(string));
dt.Columns.Add("Points", typeof(int));
DataRow row = dt.NewRow();
row[0] = "4Q'14";
row[1] = 27;
dt.Rows.Add(row);
row = dt.NewRow();
row[0] = "1Q'15";
row[1] = 0;
dt.Rows.Add(row);
row = dt.NewRow();
row[0] = "2Q'15";
row[1] = 0;
dt.Rows.Add(row);
row = dt.NewRow();
row[0] = "3Q'15";
row[1] = 0;
dt.Rows.Add(row);
row = dt.NewRow();
row[0] = "4Q'15";
row[1] = 200;
dt.Rows.Add(row);
WorkbookDesigner wd = new WorkbookDesigner();
//Create a designer workbook
Workbook workbook = new Workbook();
Worksheet worksheet = workbook.Worksheets[0];
worksheet.Cells["A1"].PutValue("Period");
worksheet.Cells["A2"].PutValue("&=Trend.Period");
worksheet.Cells["B1"].PutValue("Points");
worksheet.Cells["B2"].PutValue("&=Trend.Points");
Range range1 = worksheet.Cells.CreateRange("A2:A2");
range1.Name = "RANGE1";
Range range2 = worksheet.Cells.CreateRange("B2:B2");
range2.Name = "RANGE2";
wd.Workbook = workbook;
wd.SetDataSource(dt);
wd.Process();
//Create chart
int chartIndex = worksheet.Charts.Add(ChartType.Column, 5, 2, 29, 10);
Chart chart = worksheet.Charts[chartIndex];
//Obtain the updated ranges after processing smart markers
var r1 = workbook.Worksheets.GetRangeByName("RANGE1");
var r2 = workbook.Worksheets.GetRangeByName("RANGE2");
MessageBox.Show(r2.RefersTo);
//Add the nseries collection to a chart
chart.NSeries.Add(r2.RefersTo, true);
//Get or set the range of category axis values
chart.NSeries.CategoryData = r1.RefersTo;
chart.NSeries.IsColorVaried = true;
wd.Workbook.Save("e:\\test2\\out1chart1.xlsx");
I am working as Support developer/ Evangelist at Aspose.

Related

How to add Calculated Member to Pivot Table via Python win32

I'm trying to add a calculated column into this pivot table that is being generated via a python script with import win32com.client.
Code is posted below that is generating the pivot table. I'm not sure how to add a column. In VBA it would be wb.PivotTable.CalculatedField.Add but that didn't work (at least the syntax I tried).
I'm trying to calculate [OoCUnits] / [GrossUnits]
#Make Pivot version with four weeks data
Excel = win32com.client.gencache.EnsureDispatch('Excel.Application')
win32c = win32com.client.constants
wb = Excel.Workbooks.Open(filename)
ws3 = wb.Worksheets('Dataset')
cl1 = ws3.Cells(1,1)
cl2 = ws3.Cells(max_row,max_col)
PivotSourceRange = ws3.Range(cl1,cl2)
ws3.Activate()
PivotSourceRange.Select()
wb.Sheets.Add (After=wb.Sheets(3))
ws4 = wb.Worksheets(4)
ws4.Name = 'Pivot'
cl3 = ws4.Cells(4,1)
PivotTargetRange = ws4.Range(cl3,cl3)
PivotTableName = 'OoCPivot'
#Make Pivot Table
PivotCache = wb.PivotCaches().Create(SourceType=win32c.xlDatabase, SourceData=PivotSourceRange, Version=win32c.xlPivotTableVersion14)
PivotTable = PivotCache.CreatePivotTable(TableDestination=PivotTargetRange, TableName=PivotTableName, DefaultVersion=win32c.xlPivotTableVersion14)
PivotTable.PivotFields('Product Name').Orientation = win32c.xlRowField
PivotTable.PivotFields('Product Name').Position = 1
PivotTable.PivotFields('Customer Number').Orientation = win32c.xlPageField
PivotTable.PivotFields('Customer Number').Position = 1
PivotTable.PivotFields('Customer Name').Orientation = win32c.xlPageField
PivotTable.PivotFields('Customer Name').Position = 2
PivotTable.PivotFields('Week Ending Date').Orientation = win32c.xlColumnField
PivotTable.PivotFields('Week Ending Date').Position = 1
DataField = PivotTable.AddDataField(PivotTable.PivotFields('GrossUnits'))
DataField.NumberFormat = '#0.00'
DataField = PivotTable.AddDataField(PivotTable.PivotFields('OoCUnits'))
DataField.NumberFormat = '#0.00'
I'm inserting the values with the DataField. The script is not presenting any issues as is.
EDIT: The exact code I implemented to solve. The last two lines are just formatting. I'm including in case it helps someone else.
CalcField = PivotTable.CalculatedFields().Add('OoC Unit %','= OoCUnits / GrossUnits')
DataField = PivotTable.AddDataField(PivotTable.PivotFields('OoC Unit %'))
DataField.NumberFormat = '#%'
PivotTable.DisplayErrorString = True
Actually, the method is PivotTable.CalculatedFields().Add() according to docs. Consider placing below at bottom:
CalcField = PivotTable.CalculatedFields().Add("OC_GrossPct", "= OoCUnits / GrossUnits")
PivotTable.PivotFields("OC_GrossPct").Orientation = win32c.xlDataField

NPOI set Explicit Column Type Not working properly

I'm using NPOI Excel Library to generate a Excel file, in that Excel file i'm explicitly define column type for Columns like Date,String etc.
Im using the following code to achive this.
var row = sheet.CreateRow(currentNPOIRowIndex++);
for (var colIndex = 0; colIndex < exportData.Columns.Count; colIndex++)
{
ICell cell = null;
cell = row.CreateCell(colIndex);
if (exportData.Columns[colIndex].DataType == typeof(DateTime))
{
if (exportData.Rows[rowIndex][colIndex].ToString() != "")
{
cell.SetCellValue((DateTime)exportData.Rows[rowIndex][colIndex]);
cell.CellStyle = (NPOI.HSSF.UserModel.HSSFCellStyle)book.CreateCellStyle();
cell.CellStyle.DataFormat = book.CreateDataFormat().GetFormat("yyyyMMdd HH:mm:ss");
cell = null;
}
else
cell.SetCellValue(exportData.Rows[rowIndex][colIndex].ToString());
}
else
cell.SetCellValue(exportData.Rows[rowIndex][colIndex].ToString());
}
}
The above code works fine for 42 rows i.e. it correctly set the Column Type,but after 42 rows Column Type doesn't apply.
Any help will be highly appreciated.
you'll required to set default column style if you want to set column format for all cells of that column. Please see the below example from xssf format. Syntax may differ for your hssf format but it will give you idea what you are missing.
I am providing you from my working code. I am using NPOI version 2.2.1.0.
can you comment line //cell = null;
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("Template");
XSSFFont defaultFont = (XSSFFont)workbook.CreateFont();
defaultFont.FontHeightInPoints = (short)10;
XSSFCellStyle headerStyle = (XSSFCellStyle)workbook.CreateCellStyle();
headerStyle.WrapText = true;
XSSFCellStyle defaultStyle = (XSSFCellStyle)workbook.CreateCellStyle();
XSSFDataFormat defaultDataFormat = (XSSFDataFormat)workbook.CreateDataFormat();
defaultStyle.SetDataFormat(defaultDataFormat.GetFormat("000-000-0000"));
defaultStyle.FillBackgroundColor = IndexedColors.LightYellow.Index;
defaultStyle.FillForegroundColor = IndexedColors.LightTurquoise.Index;
defaultStyle.SetFont(defaultFont);
var row = sheet.CreateRow(0);
for (int headerCount = 0; headerCount < headers.Count(); headerCount++)
{
row.CreateCell(headerCount).SetCellValue(headers[headerCount]);
row.Cells[headerCount].CellStyle = headerStyle;
sheet.SetDefaultColumnStyle(headerCount, defaultStyle);
}

How can I shift the "subitems" in an Excel PivotTable to another column?

I generate an Excel sheet which contains data formatted like so:
IOW, the "Total Packages", "Total Purchases", "Average Price", and "% of Total" values are located in a column of their own (Data) for each overarching (or sidearching) description.
When I PivotTablize this data, it places these values beneath each description:
This makes sense, but those accustomed to the previous appearance want it to be replicated in the PivotTable. How can I shift the Description "subitems" in the PivotTable to their own column?
This is the code I use to generate the PivotTable:
private void PopulatePivotTableSheet()
{
string NORTHWEST_CORNER_OF_PIVOT_TABLE = "A6";
AddPrePivotTableDataToPivotTableSheet();
var dataRange = rawDataWorksheet.Cells[rawDataWorksheet.Dimension.Address];
dataRange.AutoFitColumns();
var pivotTable = pivotTableWorksheet.PivotTables.Add(
pivotTableWorksheet.Cells[NORTHWEST_CORNER_OF_PIVOT_TABLE],
dataRange,
"PivotTable");
pivotTable.MultipleFieldFilters = true;
pivotTable.GridDropZones = false;
pivotTable.Outline = false;
pivotTable.OutlineData = false;
pivotTable.ShowError = true;
pivotTable.ErrorCaption = "[error]";
pivotTable.ShowHeaders = true;
pivotTable.UseAutoFormatting = true;
pivotTable.ApplyWidthHeightFormats = true;
pivotTable.ShowDrill = true;
// Row field[s]
var descRowField = pivotTable.Fields["Description"];
pivotTable.RowFields.Add(descRowField);
// Column field[s]
var monthYrColField = pivotTable.Fields["MonthYr"];
pivotTable.ColumnFields.Add(monthYrColField);
// Data field[s]
var totQtyField = pivotTable.Fields["TotalQty"];
pivotTable.DataFields.Add(totQtyField);
var totPriceField = pivotTable.Fields["TotalPrice"];
pivotTable.DataFields.Add(totPriceField);
// Don't know how to calc these vals here, so have to grab them from the source data sheet
var avgPriceField = pivotTable.Fields["AvgPrice"];
pivotTable.DataFields.Add(avgPriceField);
var prcntgOfTotalField = pivotTable.Fields["PrcntgOfTotal"];
pivotTable.DataFields.Add(prcntgOfTotalField);
}
So there is one RowField ("MonthYr") with values such as "201509" and "201510", one ColumnField ("Description") and four DataFields, which align themseles under the Description column field. I want to shift those four fields to the right, to their own column, and the Description label to be vertically centered between those four values to their left. [How] is this possible?
Try changing the layout of your table with
pivotTable.RowAxisLayout xlTabularRow
pivotTable.MergeLabels = True
this is the result:
A little script in C# with Interop.Excel. Included the using ;)
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
var excelApp = new Excel.Application();
Excel.Workbook wb = excelApp.Workbooks.Open(#"e:\42\TestSO.xlsx");
Worksheet ws = wb.Worksheets["SheetName"];
PivotTable pt = ws.PivotTables("DynamicTableName");
pt.RowAxisLayout(XlLayoutRowType.xlTabularRow);
pt.MergeLabels = true;
wb.Save();
wb.Close();
Marshal.ReleaseComObject(ws);
It's all about PivotTable layout / design... here's the manual way - Salvador has the VBA way :)...

Aspose Slides Table Cell Insert HTML content

I am working with Aspose slides to generate PPT in my application, I ran into a situation where I need to insert HTML text into Table Cell, I verified all blogs no one given answer to me. If any body know here please let me know. Thanks In advance.
You can use the TextFrame's paragraph associated with each cell to insert HTML using Aspose.Slides for .NET. Check the following code:
//Instantiate Presentation class that represents PPTX file
using (Presentation pres = new Presentation())
{
//Access first slide
ISlide sld = pres.Slides[0];
//Define columns with widths and rows with heights
double[] dblCols = { 250, 250};
double[] dblRows = { 150, 130, 130 };
//Add table shape to slide
ITable tbl = sld.Shapes.AddTable(100, 50, dblCols, dblRows);
//Set border format for each cell
foreach (IRow row in tbl.Rows)
foreach (ICell cell in row)
{
cell.BorderTop.FillFormat.FillType = FillType.Solid;
cell.BorderTop.FillFormat.SolidFillColor.Color = Color.Red;
cell.BorderTop.Width = 5;
cell.BorderBottom.FillFormat.FillType = FillType.Solid;
cell.BorderBottom.FillFormat.SolidFillColor.Color = Color.Red;
cell.BorderBottom.Width = 5;
cell.BorderLeft.FillFormat.FillType = FillType.Solid;
cell.BorderLeft.FillFormat.SolidFillColor.Color = Color.Red;
cell.BorderLeft.Width = 5;
cell.BorderRight.FillFormat.FillType = FillType.Solid;
cell.BorderRight.FillFormat.SolidFillColor.Color = Color.Red;
cell.BorderRight.Width = 5;
}
//Adding html text in text frame
tbl[0, 0].TextFrame.Paragraphs.AddFromHtml(#"<html><body><p><b>This text is bold</b></p>
<p><i>This text is italic</i></p><p>This is<sub> subscript</sub> and <sup>superscript</sup></p>
</body></html>");
//Write PPTX to Disk
pres.Save("d:\\data\\table_html.pptx", Aspose.Slides.Export.SaveFormat.Pptx);
}
P.S. I am working as social media developer at Aspose.

EPPlus graph in separate sheet

How do I create a graph as a separate worksheet rather than as a drawing in an existing worksheet using EPPLus?
In version 4.0.4.0 (download the code from codeplex, for correct a bug in saving file), you can use:
workbook.Worksheets.AddChart(name, type);
this will create a sheet with only the chart.
You should do what you want. That is the chart you want to plot, plot it in the sheet you want.
ExcelPackage pck = new ExcelPackage();
ExcelRange r1, r2;
var sheet1 = pck.Workbook.Worksheets.Add("data_sheet");
var sheet2 = pck.Workbook.Worksheets.Add("chart_sheet");
var chart = (OfficeOpenXml.Drawing.Chart.ExcelBarChart)sheet2.Drawings.AddChart("some_name", OfficeOpenXml.Drawing.Chart.eChartType.ColumnClustered);
chart.Legend.Position = OfficeOpenXml.Drawing.Chart.eLegendPosition.Right;
chart.Legend.Add();
chart.SetPosition(1, 0, 1, 0);
chart.SetSize(600, 400);
chart.DataLabel.ShowValue = true;
r1 = sheet1.Cells["A3:A10"];
r2 = sheet1.Cells["B3:B10"];
chart.Series.Add(r2, r1);
chart.Style = OfficeOpenXml.Drawing.Chart.eChartStyle.Style21;
chart.Title.Text = "Some title";
chart.XAxis.Title.Text = "X axis name";
chart.YAxis.Title.Text = "Y axis name";
In this example, chart is plotted in sheet2 but data is in sheet1.
Hope this is helpful.

Resources