I am using QLNet for american option pricing, but it doesn't work.
i have posted my question on Quantlib forum
my code:
todaysDate & settlementdate = 2012-12-18, maturity = 2013-01-18,
Calendar calendar = new TARGET();
Settings.setEvaluationDate(TodaysDate);
DayCounter dayCounter = new Actual365Fixed();
Handle<Quote> underlyingH = new Handle<Quote>(new SimpleQuote(100));
var flatTermStructure = new Handle<YieldTermStructure>(new FlatForward(SettlementDate, 0.08, dayCounter));
var flatDividendTS = new Handle<YieldTermStructure>(new FlatForward(SettlementDate, 0, dayCounter));
var flatVolTS = new Handle<BlackVolTermStructure>(new BlackConstantVol(SettlementDate, calendar, 0.2, dayCounter));
StrikedTypePayoff payoff = new PlainVanillaPayoff(Call, 101);
var bsmProcess = new BlackScholesMertonProcess(underlyingH, flatDividendTS, flatTermStructure, flatVolTS);
Exercise exerciseEngine = exerciseEngine = new AmericanExercise(SettlementDate, Maturity);
VanillaOption optionEngine = new VanillaOption(payoff, exerciseEngine);
optionEngine.setPricingEngine(new BinomialVanillaEngine<CoxRossRubinstein>(bsmProcess, 801));
//error:
optionEngine.impliedVolatility(optionEngine.NPV(), bsmProcess, 1.0e-4, 100, 1.0e-7, 4.0);
underlying = 100, k=101, i=0.08, vol=0.2,div=0,
todaysDate & settlementdate = 2012-12-18, maturity = 2013-01-18,
In VanillaOption.cs, the code of case Exercise.Type.American is uncomment;
The error message is: An item with the same key has already been added.
at line 111 (results.additionalResults.Add priceCurve, prices_) in FDStepConditionEngine.cs
Thanks for kindly help.
Related
I am developing a program that has the feature to dynamically create DocX files. As the title suggests, I am having a problem inserting images into a DocX file. One of the issues, as I see it, is that I am using C# 2.0. (When answering this question, I would like to stress that I do not wish to switch to C# 3.0, so please do not try to persuade me.)
I have taken a look at the MSDN article at http://msdn.microsoft.com/en-us/library/office/bb497430.aspx, but when I converted the C# 3.0 code that MSDN uses to C# 2.0, I get a document that does not open, and it gives me the error: "The file Testing.docx cannot be opened because there are problems with the contents," and "No error detail available."
Here is my code:
ImagePart ip_Part;
WordprocessingDocument wpd_Doc = WordprocessingDocument.Create("C:\\Convert\\Testing.docx", WordprocessingDocumentType.Document);
public Testing()
{
wpd_Doc.AddMainDocumentPart();
wpd_Doc.MainDocumentPart.Document = new Document();
wpd_Doc.MainDocumentPart.Document.Body = new Body();
ip_Part = wpd_Doc.MainDocumentPart.AddImagePart(ImagePartType.Png);
System.IO.FileStream fs_Stream = new System.IO.FileStream("image.png", System.IO.FileMode.Open);
ip_Part.FeedData(fs_Stream);
AddImageToBody("image.png", wpd_Doc.MainDocumentPart.GetIdOfPart(ip_Part));
AppendText("Here is a test bulleted list:");
wpd_Doc.MainDocumentPart.Document.Save();
//Close the document.
wpd_Doc.Close();
}
private void AddImageToBody(string s_ImagePath, string s_RelationshipId)
{
//OpenXmlElement oxe_Element = new Numbering();
Drawing d_Drawing = new Drawing();
DrawWord.Inline i_Inline = new DrawWord.Inline();
DrawWord.Extent e_Extent = new DrawWord.Extent();
e_Extent.Cx = 600075; //63px / 96dpi * 914400
e_Extent.Cy = 600075; //63px / 96dpi * 914400
i_Inline.Extent = e_Extent;
DrawWord.DocProperties dp_Prop = new DrawWord.DocProperties();
//dp_Prop.Id = uint.Parse(System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString());
dp_Prop.Id = 1;
dp_Prop.Name = "Picture 1";
dp_Prop.Description = "An automated image.";
i_Inline.DocProperties = dp_Prop;
DrawWord.NonVisualGraphicFrameDrawingProperties nvgfdp_Prop = new DrawWord.NonVisualGraphicFrameDrawingProperties();
Draw.GraphicFrameLocks gfl_Locks = new Draw.GraphicFrameLocks();
gfl_Locks.NoChangeAspect = true;
nvgfdp_Prop.GraphicFrameLocks = gfl_Locks;
i_Inline.NonVisualGraphicFrameDrawingProperties = nvgfdp_Prop;
Draw.Graphic g_Graphic = new Draw.Graphic();
Draw.GraphicData gd_Data = new DocumentFormat.OpenXml.Drawing.GraphicData();
gd_Data.Uri = DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
DrawPic.Picture p_Pic = new DrawPic.Picture();
DrawPic.NonVisualPictureProperties nvpp_Prop = new DrawPic.NonVisualPictureProperties();
DrawPic.NonVisualDrawingProperties nvdp_Prop = new DrawPic.NonVisualDrawingProperties();
nvdp_Prop.Id = uint.Parse(System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString());
//nvdp_Prop.Name = s_ImagePath;
nvdp_Prop.Name = "New_Image.png";
nvpp_Prop.NonVisualDrawingProperties = nvdp_Prop;
DrawPic.NonVisualPictureDrawingProperties nvpdp_Prop = new DrawPic.NonVisualPictureDrawingProperties();
nvpp_Prop.NonVisualPictureDrawingProperties = nvpdp_Prop;
p_Pic.NonVisualPictureProperties = nvpp_Prop;
DrawPic.BlipFill bf_Fill = new DrawPic.BlipFill();
Draw.Blip b_Blip = new Draw.Blip();
Draw.ExtensionList el_List = new Draw.ExtensionList();
Draw.BlipExtension be_Extension = new Draw.BlipExtension();
be_Extension.Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}";
el_List.Append(be_Extension);
b_Blip.Append(el_List);
b_Blip.Embed = s_RelationshipId;
b_Blip.CompressionState = Draw.BlipCompressionValues.Print;
bf_Fill.Blip = b_Blip;
Draw.Stretch s_Stretch = new Draw.Stretch();
Draw.FillRectangle fr_Rect = new Draw.FillRectangle();
s_Stretch.FillRectangle = fr_Rect;
bf_Fill.Append(s_Stretch);
p_Pic.BlipFill = bf_Fill;
DrawPic.ShapeProperties sp_Prop = new DrawPic.ShapeProperties();
Draw.Transform2D t2d_Transform = new Draw.Transform2D();
Draw.Offset o_Offset = new Draw.Offset();
o_Offset.X = 0;
o_Offset.Y = 0;
t2d_Transform.Offset = o_Offset;
Draw.Extents e_Extents = new Draw.Extents();
e_Extents.Cx = 600075; //63px / 96dpi * 914400
e_Extents.Cy = 600075; //63px / 96dpi * 914400
t2d_Transform.Extents = e_Extents;
sp_Prop.Transform2D = t2d_Transform;
Draw.PresetGeometry pg_Geom = new Draw.PresetGeometry();
Draw.AdjustValueList avl_List = new Draw.AdjustValueList();
pg_Geom.AdjustValueList = avl_List;
pg_Geom.Preset = Draw.ShapeTypeValues.Rectangle;
sp_Prop.Append(pg_Geom);
p_Pic.ShapeProperties = sp_Prop;
gd_Data.Append(p_Pic);
g_Graphic.GraphicData = gd_Data;
i_Inline.Graphic = g_Graphic;
d_Drawing.Inline = i_Inline;
//oxe_Element.Append(d_Drawing);
//Run r_Run = new Run(d_Drawing);
wpd_Doc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(d_Drawing)));
}
(The variable names are bad, but this was just a test program, so I did not spend too much time. Also, I have the lines spaced to mimic the Xml format that MSDN had in its example. If I could use the C# 3.0 syntax, I would, but I am using Visual Studio 2005.)
I have found the answer. Surprisingly, I did not find this webpage--because it was some Google pages down with some odd keyword searching--that completely worked: http://blog.stuartwhiteford.com/?p=33. Though it is written with Collection Initializations, I was able to change them to fit C# 2.0 standards.
I am trying to send a PurchaseOrder created with Intuit .NET SDK v3. I found a suitable example with Invoice: how to add invoice or sales receipt quickbooks rest api v3.0
But I cannot work out what I need to do to make it working for Purchase Order. I am getting BadRequest no matter what properties do I set.
DataService commonService = new DataService(context);
QueryService<Vendor> accountQueryService = new QueryService<Vendor>(context);
Vendor customer = accountQueryService.Where(x => x.Id == "9").FirstOrDefault<Vendor>();
QueryService<Item> itemQueryService = new QueryService<Item>(context);
Item item = itemQueryService.Where(x => x.Id == "1").FirstOrDefault<Item>();
PurchaseOrder invoice = new PurchaseOrder();
invoice.VendorRef = new ReferenceType()
{
name = customer.DisplayName,
Value = customer.Id
};
/*invoice.APAccountRef = new ReferenceType()
{
type = Enum.GetName(typeof(objectNameEnumType), objectNameEnumType.Account),
name = "Account Receivable",
Value = "QB:37"
};*/
List<Line> lineList = new List<Line>();
Line line = new Line();
line.Description = "Description";
line.Amount = new Decimal(100.00);
line.AmountSpecified = true;
//line.DetailType = LineDetailTypeEnum.DescriptionOnly;
//line.DetailTypeSpecified = true;
line.DetailType = LineDetailTypeEnum.PurchaseOrderItemLineDetail;
line.DetailTypeSpecified = true;
PurchaseOrderItemLineDetail det = new PurchaseOrderItemLineDetail();
det.Qty = 10;
det.QtySpecified = true;
det.ItemRef = new ReferenceType()
{
name = item.Name,
Value = item.Id
};
line.AnyIntuitObject = det;
lineList.Add(line);
invoice.Line = lineList.ToArray();
I've tried to set account and use just description in the line without success. If I add PurchaseOrder created with the above code I am getting BadRequest error with Validation exception inside.
Can please somebody point me in the right direction here. I am probably missing some PurchaseOrder property.
I am using the August V3 SDK loaded using NuGet.
UPDATE
This is c# translation of the XML suggested by Manas Mukherjee below
DataService commonService = new DataService(context);
QueryService<Vendor> accountQueryService = new QueryService<Vendor>(context);
Vendor customer = accountQueryService.Where(x => x.Id == "9").FirstOrDefault<Vendor>();
QueryService<Item> itemQueryService = new QueryService<Item>(context);
Item item = itemQueryService.Where(x => x.Id == "1").FirstOrDefault<Item>();
PurchaseOrder invoice = new PurchaseOrder();
invoice.TxnDate = DateTime.Now;
invoice.TxnDateSpecified = true;
invoice.Memo = "For Internal usage";
invoice.GlobalTaxCalculation = GlobalTaxCalculationEnum.TaxInclusive;
invoice.GlobalTaxCalculationSpecified = true;
invoice.ReplyEmail = new EmailAddress();
invoice.ReplyEmail.Address = "testing#testing.com";
invoice.ReplyEmail.Default = false;
invoice.ReplyEmail.DefaultSpecified = true;
invoice.ReplyEmail.Tag = "Home";
invoice.ShipAddr = new PhysicalAddress();
invoice.ShipAddr.Line1 = "shippingToAddr1Sat Oct 19 09:48:52 IST 2013";
invoice.ShipAddr.Line2 = "shippingToAddr2Sat Oct 19 09:48:52 IST 2013";
invoice.ShipAddr.Line3 = "shippingToAddr3Sat Oct 19 09:48:52 IST 2013";
invoice.ShipAddr.City = "Bangalore";
invoice.ShipAddr.Country = "India";
invoice.ShipAddr.CountrySubDivisionCode = "KA";
invoice.ShipAddr.PostalCode = "560045";
invoice.POEmail = new EmailAddress();
invoice.POEmail.Address = "testing#testing.com";
invoice.POEmail.Default = true;
invoice.POEmail.DefaultSpecified = true;
invoice.POEmail.Tag = "Business";
invoice.VendorRef = new ReferenceType()
{
name = customer.DisplayName,
Value = customer.Id
};
invoice.TotalAmt = new Decimal(100.00);
invoice.TotalAmtSpecified = true;
invoice.APAccountRef = new ReferenceType()
{
//type = Enum.GetName(typeof(objectNameEnumType), objectNameEnumType.Account),
name = "Accounts Payable (A/P)",
Value = "32"
};
List<Line> lineList = new List<Line>();
Line line = new Line();
line.Amount = new Decimal(100.00);
line.AmountSpecified = true;
line.DetailType = LineDetailTypeEnum.AccountBasedExpenseLineDetail;
line.DetailTypeSpecified = true;
AccountBasedExpenseLineDetail det = new AccountBasedExpenseLineDetail();
det.AccountRef = new ReferenceType()
{
name = "Accounts Payable (A/P)",
Value = "32"
};
line.AnyIntuitObject = det;
/*PurchaseOrderItemLineDetail det = new PurchaseOrderItemLineDetail();
det.Qty = 10;
det.QtySpecified = true;
det.ItemRef = new ReferenceType()
{
name = item.Name,
Value = item.Id
};
line.AnyIntuitObject = det;*/
lineList.Add(line);
invoice.Line = lineList.ToArray();
return invoice;
Unfortunately I am still getting BadRequest error.
UPDATE 2
After some more testing I found out that it gives error because of APAccountRef property. It's OK without setting up this property.
The other issue came when I tried to use PurchaseOrderItemLineDetail in lines. Not sure if this type is correct (based on the name it looks like one) but using this details type is causing BadRequest error. Using ItemBasedExpenseLineDetail is a workaround.
I will set Manas answer as correct since it gave me a direction to investigate further. But big thanks to Nimisha Shrivastava for the help with logging.
Here is one working PurchaseOrder create request XML.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PurchaseOrder domain="QBO" xmlns="http://schema.intuit.com/finance/v3">
<TxnDate>2013-10-19</TxnDate>
<Line>
<Amount>3.00</Amount>
<DetailType>AccountBasedExpenseLineDetail</DetailType>
<AccountBasedExpenseLineDetail>
<AccountRef name="Accounts Payable (A/P)">32</AccountRef>
</AccountBasedExpenseLineDetail>
</Line>
<VendorRef name="TestDataVendor926e8Sample1">1386</VendorRef>
<TotalAmt>3.00</TotalAmt>
<ReplyEmail>
<Address>testing#testing.com</Address>
<Default>false</Default>
<Tag>Home</Tag>
</ReplyEmail>
<Memo>For Internal usage</Memo>
<GlobalTaxCalculation>TaxInclusive</GlobalTaxCalculation>
<ShipAddr>
<Line1>shippingToAddr1Sat Oct 19 09:48:52 IST 2013</Line1>
<Line2>shippingToAddr2Sat Oct 19 09:48:52 IST 2013</Line2>
<Line3>shippingToAddr3Sat Oct 19 09:48:52 IST 2013</Line3>
<City>Bangalore</City>
<Country>India</Country>
<CountrySubDivisionCode>KA</CountrySubDivisionCode>
<PostalCode>560045</PostalCode>
</ShipAddr>
<POEmail>
<Address>test#testing.com</Address>
<Default>true</Default>
<Tag>Business</Tag>
</POEmail>
</PurchaseOrder>
I've used java devkit(PFB code). Hope you'll find similar properties in .net devkit.
public PurchaseOrder purchaseOrderWithAllProperties() throws FMSException, ParseException {
PurchaseOrder purchaseOrder = new PurchaseOrder();
purchaseOrder.setVendorRef(this.vendorRef);
purchaseOrder.setMemo("For Internal usage");
Line line1 = new Line();
line1.setAmount(new BigDecimal("3.00"));
line1.setDetailType(LineDetailTypeEnum.ACCOUNT_BASED_EXPENSE_LINE_DETAIL);
AccountBasedExpenseLineDetail detail = new AccountBasedExpenseLineDetail();
ReferenceType expenseAccountRef = this.accountRef;
detail.setAccountRef(expenseAccountRef);
line1.setAccountBasedExpenseLineDetail(detail);
List<Line> lines1 = new ArrayList<Line>();
lines1.add(line1);
purchaseOrder.setLine(lines1);
EmailAddress emailAddr = new EmailAddress();
emailAddr.setAddress("test#testing.com");
emailAddr.setDefault(true);
emailAddr.setTag("Business");
purchaseOrder.setPOEmail(emailAddr);
//purchaseOrder.setDueDate(DateUtils.getDateWithNextDays(45));
purchaseOrder.setDomain("QBO");
//purchaseOrder.setExchangeRate(new BigDecimal("20.00"));
purchaseOrder.setGlobalTaxCalculation(GlobalTaxCalculationEnum.TAX_INCLUSIVE);
EmailAddress replyEmail = new EmailAddress();
replyEmail.setAddress("testing#testing.com");
replyEmail.setDefault(false);
replyEmail.setTag("Home");
purchaseOrder.setReplyEmail(replyEmail);
PhysicalAddress shipAddr = new PhysicalAddress();
shipAddr.setLine1("shippingToAddr1" + DateUtils.getCurrentDateTime());
shipAddr.setLine2("shippingToAddr2" + DateUtils.getCurrentDateTime());
shipAddr.setLine3("shippingToAddr3" + DateUtils.getCurrentDateTime());
shipAddr.setCity("Bangalore");
shipAddr.setCountry("India");
shipAddr.setCountrySubDivisionCode("KA");
shipAddr.setPostalCode("560045");
purchaseOrder.setShipAddr(shipAddr);
//purchaseOrder.setStatus(EntityStatusEnum.IN_TRANSIT);
purchaseOrder.setTotalAmt(new BigDecimal("3.00"));
purchaseOrder.setTxnDate(DateUtils.getCurrentDateTime());
return purchaseOrder;
}
Thanks
Try this one adding purchase order.
PurchaseOrder po = new PurchaseOrder();
po.ReplyEmail = new EmailAddress();
po.ReplyEmail.Address = "kalpana.kodavaluru#gmail.com";
po.ReplyEmail.Default = false;
po.ReplyEmail.DefaultSpecified = true;
po.ReplyEmail.Tag = "Home";
po.ShipAddr = new PhysicalAddress();
po.ShipAddr.Line1 = "shippingToAddr1Sat Oct 19 09:48:52 IST 2013";
po.ShipAddr.Line2 = "shippingToAddr2Sat Oct 19 09:48:52 IST 2013";
po.ShipAddr.Line3 = "shippingToAddr3Sat Oct 19 09:48:52 IST 2013";
po.ShipAddr.City = "Bangalore";
po.ShipAddr.Country = "India";
po.ShipAddr.CountrySubDivisionCode = "KA";
po.ShipAddr.PostalCode = "560045";
po.POEmail = new EmailAddress();
po.POEmail.Address = "testing#testing.com";
po.POEmail.Default = true;
po.POEmail.DefaultSpecified = true;
po.POEmail.Tag = "Business";
po.VendorRef = new ReferenceType()
{
name = supplier.DisplayName,
Value = supplier.Id
};
po.TotalAmt = new Decimal(100.00);
po.TotalAmtSpecified = true;
List<Line> lineList1 = new List<Line>();
Line line1 = new Line();
line1.Id = "1";
line1.Amount = new Decimal(100.00);
line1.AmountSpecified = true;
line1.DetailType = LineDetailTypeEnum.ItemBasedExpenseLineDetail;
line1.DetailTypeSpecified = true;
ItemBasedExpenseLineDetail det = new ItemBasedExpenseLineDetail();
det.ItemRef = new ReferenceType()
{
name = item.Name,
Value = item.Id
};
det.Qty = new decimal(1);
det.QtySpecified = true;
det.ItemElementName = ItemChoiceType.UnitPrice;
det.AnyIntuitObject = new decimal(100);
det.BillableStatus = new BillableStatusEnum();
line1.AnyIntuitObject = det;
lineList1.Add(line1);
po.Line = lineList1.ToArray();
try
{
var podata=commonService.Add(po);
}
catch (Exception ex)
{
throw ex;
}
Is it possible to change CreationDateTime, SentDateTime, etc.????
I`m tring to create/update message. All run fine, but i need to set field ItemType.CreateDateTime with my values (eg. I need to create message that has time creation not today, but year ego).
I have next code:
//Update created item
ItemIdType itemId = new ItemIdType();
itemId.Id = savedMessageId;
itemId.ChangeKey = savedMessageChangeKey;
ItemType setCreateDT = new ItemType();
setCreateDT.DateTimeCreated = new System.DateTime(2000, 10, 10, 12, 12, 12);
setCreateDT.DateTimeCreatedSpecified = true;
SetItemFieldType setItemField = new SetItemFieldType();
setItemField.Item = new PathToUnindexedFieldType();
(setItemField.Item as PathToUnindexedFieldType).FieldURI = UnindexedFieldURIType.itemDateTimeCreated;
setItemField.Item1 = setCreateDT;
UpdateItemType request = new UpdateItemType();
request.ItemChanges = new ItemChangeType[1] { new ItemChangeType() };
request.ItemChanges[0].Item = itemId;
request.ItemChanges[0].Updates = new ItemChangeDescriptionType[1];
request.ItemChanges[0].Updates[0] = setItemField;
request.MessageDisposition = MessageDispositionType.SaveOnly;
request.MessageDispositionSpecified = true;
UpdateItemResponseType updateItemResponse = m_mailbox.UpdateItem(request);
That request return Error: "Set action is invalid for property."
If im tring to change Subject, all run OK.
[UPDATE]
Found next solution, but it doesn`t work.
There is using extended properties and their ids.
PathToExtendedFieldType q = new PathToExtendedFieldType();
q.PropertyId = 3590; //DeliveryTime
q.PropertyType = MapiPropertyTypeType.SystemTime;
q.PropertyIdSpecified = true;
newItem.ExtendedProperty[0] = new ExtendedPropertyType();
newItem.ExtendedProperty[0].ExtendedFieldURI = q;
newItem.ExtendedProperty[0].ExtendedFieldURI.DistinguishedPropertySetIdSpecified = true;
newItem.ExtendedProperty[0].Item = new System.DateTime(2013, 5, 5, 5, 5, 5).ToString("yyyy-MM-ddTHH:mm:ssZ");
...
CreateItemResponseType createItemResponse = m_mailbox.CreateItem(createItemType);
It works fine, but i don`t see any changes..
Second solution is correct, but there are some mistakes.
1) It's better to get access to properties by PropertyTag.
2) You should only set up PropertyTag and PropertyType.
Here is working code:
ItemType newItem = xmlParser.LoadItem(); //info for newItem takes from xml
newItem.ExtendedProperty = new ExtendedPropertyType[1];
PathToExtendedFieldType q = new PathToExtendedFieldType();
q.PropertyTag = "3590"; //DeliveryTime
q.PropertyType = MapiPropertyTypeType.SystemTime;
newItem.ExtendedProperty[0] = new ExtendedPropertyType();
newItem.ExtendedProperty[0].ExtendedFieldURI = q;
newItem.ExtendedProperty[0].Item = new System.DateTime(2014, 5, 5, 5, 5, 5).ToString("yyyy-MM-ddTHH:mm:ssZ");
Does anyone know how to do this?
I'm using EPPlus in .Net and have created a pivot table with 2 row fields and one summary datafield:
Dim Pivot As OfficeOpenXml.Table.PivotTable.ExcelPivotTable
Pivot = wksPivot.PivotTables.Add(wksPivot.Cells("A1"), Datarange, "pName")
Pivot.RowFields.Add(Pivot.Fields("Fld1")).Sort = Table.PivotTable.eSortType.Ascending
Pivot.RowFields.Add(Pivot.Fields("Fld2")).Sort = Table.PivotTable.eSortType.Ascending
Dim dtaFld As OfficeOpenXml.Table.PivotTable.ExcelPivotTableDataField
dtaFld = Pivot.DataFields.Add(Pivot.Fields("XYZ"))
dtaFld.Function = Table.PivotTable.DataFieldFunctions.Sum
Everything works great, but I want to have the Pivot Table start off as collapsed when the user opens the workbook (In excel, when you're creating the pivot table, you can right-click in the data element and select "Expand / Collapse" > "Collapse Entire Field"
Hot can I do this via code?? (And I'm willing to use direct OpenXML if EPPlus doesn't support this yet...)
ALSO, is there a way to delete out the Raw data from the workbook so that the pivot table still works? i've tried and when I open the workbook, my pivot table is blank? - My current logic has led me to this question... Any thoughts??
(I do know I wrote this question in VB. but I added both the C# & VB tags to this question - I'm comfortable with code in either language - Thanks!!)
Could make it xlsm and add vba to it. This is probably the worst answer to this solution but it achives full collapse. I have provided a working example, just copy past into a new console app. add the epplus dependency, "F5".
modified/taken from http://epplus.codeplex.com/SourceControl/latest#SampleApp/Sample15.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OfficeOpenXml.Table;
using OfficeOpenXml.Table.PivotTable;
using OfficeOpenXml;
using System.IO;
namespace pTable
{
class Program
{
static void Main(string[] args)
{
//ExcelPackage _pck = new ExcelPackage();
Directory.CreateDirectory(string.Format("Test"));
//ExcelPackage _pck = new ExcelPackage(new FileInfo("Test\\Worksheet.xlsx"));
ExcelPackage _pck = new ExcelPackage(new FileInfo("Test\\Worksheet.xlsm"));
var wsPivot1 = _pck.Workbook.Worksheets.Add("Rows-Data on columns");
var ws = _pck.Workbook.Worksheets.Add("Data");
ws.Cells["K1"].Value = "Item";
ws.Cells["L1"].Value = "Category";
ws.Cells["M1"].Value = "Stock";
ws.Cells["N1"].Value = "Price";
ws.Cells["O1"].Value = "Date for grouping";
ws.Cells["K2"].Value = "Crowbar";
ws.Cells["L2"].Value = "Hardware";
ws.Cells["M2"].Value = 12;
ws.Cells["N2"].Value = 85.2;
ws.Cells["O2"].Value = new DateTime(2010, 1, 31);
ws.Cells["K3"].Value = "Crowbar";
ws.Cells["L3"].Value = "Hardware";
ws.Cells["M3"].Value = 15;
ws.Cells["N3"].Value = 12.2;
ws.Cells["O3"].Value = new DateTime(2010, 2, 28);
ws.Cells["K4"].Value = "Hammer";
ws.Cells["L4"].Value = "Hardware";
ws.Cells["M4"].Value = 550;
ws.Cells["N4"].Value = 72.7;
ws.Cells["O4"].Value = new DateTime(2010, 3, 31);
ws.Cells["K5"].Value = "Hammer";
ws.Cells["L5"].Value = "Hardware";
ws.Cells["M5"].Value = 120;
ws.Cells["N5"].Value = 11.3;
ws.Cells["O5"].Value = new DateTime(2010, 4, 30);
ws.Cells["K6"].Value = "Crowbar";
ws.Cells["L6"].Value = "Hardware";
ws.Cells["M6"].Value = 120;
ws.Cells["N6"].Value = 173.2;
ws.Cells["O6"].Value = new DateTime(2010, 5, 31);
ws.Cells["K7"].Value = "Hammer";
ws.Cells["L7"].Value = "Hardware";
ws.Cells["M7"].Value = 1;
ws.Cells["N7"].Value = 4.2;
ws.Cells["O7"].Value = new DateTime(2010, 6, 30);
ws.Cells["K8"].Value = "Saw";
ws.Cells["L8"].Value = "Hardware";
ws.Cells["M8"].Value = 4;
ws.Cells["N8"].Value = 33.12;
ws.Cells["O8"].Value = new DateTime(2010, 6, 28);
ws.Cells["K9"].Value = "Screwdriver";
ws.Cells["L9"].Value = "Hardware";
ws.Cells["M9"].Value = 1200;
ws.Cells["N9"].Value = 45.2;
ws.Cells["O9"].Value = new DateTime(2010, 8, 31);
ws.Cells["K10"].Value = "Apple";
ws.Cells["L10"].Value = "Groceries";
ws.Cells["M10"].Value = 807;
ws.Cells["N10"].Value = 1.2;
ws.Cells["O10"].Value = new DateTime(2010, 9, 30);
ws.Cells["K11"].Value = "Butter";
ws.Cells["L11"].Value = "Groceries";
ws.Cells["M11"].Value = 52;
ws.Cells["N11"].Value = 7.2;
ws.Cells["O11"].Value = new DateTime(2010, 10, 31);
ws.Cells["O2:O11"].Style.Numberformat.Format = "yyyy-MM-dd";
var pt = wsPivot1.PivotTables.Add(wsPivot1.Cells["A1"], ws.Cells["K1:N11"], "Pivottable1");
pt.Compact = true;
pt.CompactData = true;
pt.GrandTotalCaption = "Total amount";
pt.RowFields.Add(pt.Fields[1]);
pt.RowFields.Add(pt.Fields[0]);
pt.DataFields.Add(pt.Fields[3]);
pt.DataFields.Add(pt.Fields[2]);
pt.DataFields[0].Function = DataFieldFunctions.Product;
pt.DataOnRows = false;
_pck.Workbook.CreateVBAProject();
var sb = new StringBuilder();
sb.AppendLine("Private Sub Workbook_Open()");
sb.AppendLine(" Range(\"A1\").Select");
sb.AppendLine(" ActiveSheet.PivotTables(\"Pivottable1\").PivotFields(\"Category\").PivotItems(\"Hardware\").ShowDetail = False");
sb.AppendLine("End Sub");
_pck.Workbook.CodeModule.Code = sb.ToString();
_pck.Save();
}
}
}
Using EPPlus you could try something like (Taken from this SO post):
(from pf in pivot.Fields
select pf).ToList().ForEach(f =>
{
f.Compact = false;
f.Outline = false;
});
or perhaps more simply, doesn't something like the following work?
pvtTable.Compact = False
pvtTable.CompactData = False
pvtTable.Outline = False
pvtTable.OutlineData = False
pvtTable.ShowDrill = True
Also look at this SO post detailing a nice reverse engineer method for seeing how excel achieves 'things'.
P.S. Can't help you with your other 'also' question sorry.
I've been trying to update a calendar with an event but it doesn't seem to be going through. could you comment on whether I'm formatting my event correctly? I've been struggling with this for some time now.
private void InsertEventIntoCalendar()
{
List<EventAttendee> ef = new List<EventAttendee>();
ef.Add(new EventAttendee{ Email = "event#gmail.com"});
List<EventReminder> eventReminder = new List<EventReminder>();
eventReminder.Add(new EventReminder{ Minutes = 4, Method = "email"});
Event.RemindersData de = new Event.RemindersData();
de.Overrides = eventReminder;
Event newEvent = new Event
{
Attendees = ef,
Reminders = de,
Summary = "Tin Roof",
Description = "Its gonna be epic",
Location = "Claremont",
Start = new EventDateTime
{
Date = "2012-09-30",
DateTime = "2012-09-30T10:00:00.000-02:00",
TimeZone = "Cape Town"
},
End = new EventDateTime
{
Date = "2012-09-30",
DateTime = new DateTime( "2012-09-30T10:25:00.000-02:00",
TimeZone = "Cape Town"
},
};
_service.Events.Insert(newEvent, "event#gmail.com").Fetch();
}
Just in case it helps anyone else. I figured out how to solve this. I was looking for the answer as well and stumbled on a solution:
public static void GCalAdd(string summary, string location, string description,
DateTime start, DateTime end, List<EventAttendee> attendees)
{
try
{
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description)
{
ClientIdentifier = ClientCredentials.ClientID,
ClientSecret = ClientCredentials.ClientSecret
};
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication);
var service = new CalendarService(auth);
var curTimeZone = TimeZone.CurrentTimeZone;
var dateOffsetStart = new DateTimeOffset(start, curTimeZone.GetUtcOffset(start));
var dateOffsetEnd = new DateTimeOffset(end, curTimeZone.GetUtcOffset(end));
var startTimeString = dateOffsetStart.ToString("o");
var endTimeString = dateOffsetEnd.ToString("o");
var evt = new Event
{
Summary = summary,
Location = location,
Description = description,
Start = new EventDateTime { DateTime = startTimeString },
End = new EventDateTime { DateTime = endTimeString },
Attendees = attendees,
};
var insert = service.Events.Insert(evt, "primary").Fetch();
if (insert != null)
{
MessageBox.Show(#"calendar item inserted");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
And, to use it, do something like the following:
var ea = new EventAttendee
{
DisplayName = "testname",
Email = "email#gmail.com",
Organizer = false,
Resource = false
};
var ea2 = new EventAttendee
{
DisplayName = "testname2",
Email = "email2#gmail.com",
Organizer = true,
Resource = false
};
var list = new List<EventAttendee> { ea, ea2 };
var now = DateTime.Now;
var t30 = now + TimeSpan.FromMinutes(30);
Program.GCalAdd("test event", "test location", "test description", now, t30, list);
I think error in reminder data. Look here - Google Calendar API v3 with C# - Unable to insert recurrence exceptions.