AddDataField function fails with Microsoft.Office.Interop.Excel - excel-interop

I am trying to recreate VBA code in C# to generate a pivot table
The VBA code is
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:= xlDatabase, SourceData:= _
"Sheet1!R1C1:R6C4", Version:= 6).CreatePivotTable TableDestination:= _
"Sheet2!R3C1", TableName:= "PivotTable1", DefaultVersion:= 6
Sheets("Sheet2").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("First Name")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables(_
"PivotTable1").PivotFields("Salary"), "Sum of Salary", xlSum
using Excel = Microsoft.Office.Interop.Excel;
...
//Start of pivot code
workbook.Worksheets.Add();
//ideally would want a "used range" here not specific cell addresses Sheet1!R1C1:R6C4
pivotcache = (Excel.PivotCache)excel.ActiveWorkbook.PivotCaches().Create(Excel.XlPivotTableSourceType.xlDatabase, "Sheet1!R1C1:R6C4", 6); // Const xlDatabase = 1 Member of Excel.XlPivotTableSourceType
pivot = pivotcache.CreatePivotTable("Sheet2!R3C1", "PivotTable1", 6);
sheet = (Excel.Worksheet) workbook.Worksheets["Sheet2"];
range = sheet.get_Range("A3");
range.Select();
pf = pivot.PivotFields("First Name");
pf.Orientation=XlPivotFieldOrientation.xlRowField; //1=xlrowfield
pf.Position = 1;
//*****Code fails here ***
df = pivot.AddDataField(pivot.PivotFields("Salary"), "Sum of Salary", XlConsolidationFunction.xlSum); //Const xlSum = -4157 (&HFFFFEFC3) Member of Excel.XlConsolidationFunction
The last line fails with console error message: Error: Operation is not supported on this platform. Line: System.Private.CoreLib
Can anyone give me some pointers?

Disaggregating the code and adding orientation xlDataField like this worked
df = pivot.PivotFields("Salary");
df.Orientation = XlPivotFieldOrientation.xlDataField;
df.Function = Excel.XlConsolidationFunction.xlSum;
df.Caption = "Sum of Salary";

Related

Google ads script Failed due to system errors

I have a Google ads script that will find any ad groups with on active RSA's, and export the campaigns and ad group name to a Google Sheet.
But sometimes then it runs it says it "Failed due to system errors" and gives the following error message:
7/11/2022 3:50:02 PM Exception: Call to GoogleAdsService.Search failed: The request took too long to respond.
at adsapp_compiled:18112:138
at adsapp_compiled:18123:9
at sa (adsapp_compiled:227:15)
at Object.search (adsapp_compiled:235:20)
at iI.search (adsapp_compiled:18238:36)
at SH.search (adsapp_compiled:17815:19)
at TH.search (adsapp_compiled:17910:20)
at $H.search (adsapp_compiled:18002:19)
at fd (adsapp_compiled:1041:32)
at fd.next ()
I think it is a runtime error, because it doesn't receive any response from the server.
i have been told it might have something to do with the syntax order, but i don't know how to fix that if that is the case.
I have tried to do the export to a new clear sheet, just to see if the sheet i used had to many formulas in it which could slow it down, but it still gave the same error message.
I have also tried to do it on an entirely different account that is smaller but still same issue.
/**********************
RSA Checker
**********************/
var SPREADSHEET_URL = 'INSERT SPREADSHEET URL HERE';
var Sheet_name = 'INSERT SHEET NAME HERE';
function main() {
var sheet = SpreadsheetApp.openByUrl(SPREADSHEET_URL).getSheetByName(Sheet_name);
var range = sheet.getRangeList(['A1:A', 'B1:B'])
range.clearContent();
sheet.getRange("A1").setValue("Campaign");
sheet.getRange("B1").setValue("Ad groups");
var GetAdGroups = AdWordsApp.adGroups()
.withCondition('Status = ENABLED')
.withCondition('CampaignStatus = ENABLED')
.withCondition("AdvertisingChannelType = SEARCH")
.withCondition("CampaignName DOES_NOT_CONTAIN_IGNORE_CASE 'dsa'")
.withCondition("AdGroupName DOES_NOT_CONTAIN_IGNORE_CASE 'dsa'")
.withCondition("campaign.experiment_type = BASE")
.get();
for (var row = 2; GetAdGroups.hasNext(); row ++) {
var AdGroups = GetAdGroups.next();
var RSACount = AdGroups.ads().withCondition('Type=RESPONSIVE_SEARCH_AD').withCondition('Status = ENABLED').get().totalNumEntities();
if ((RSACount < 1)) {
sheet.appendRow( [AdGroups.getCampaign().getName(), AdGroups.getName()] );
}
}
}

GSheets Trigger for updating entries wont work - Script does work manually tho

I want to run a script for GSheets by a trigger every minute.
The script works without an error if I run it manually, but the trigger will throw an error message 100% of the time.
The idea is to populate a spreadsheet via GForms. The script should update the entries when a new form of an existing data set is submitted (identifier is in row 4). It does this by looking for duplicates and deleting the old set of data.
The trigger should run the script every minute or so to ensure data quality and to eliminate multiple duplicates if they occur.
This is the code for my script:
function updateExisting(columnWithUniqueIdentifier,sheetTabName) {
var dataFromColumnToMatch,lastColumn,lastRow,rowWithExistingUniqueValue,rowOfDataJustSaved,
sh,ss,valueToSearchFor;
// USER SETTINGS - if the values where not passed in to the function
if (!columnWithUniqueIdentifier) {//If you are not passing in the column number
columnWithUniqueIdentifier = 4;//Hard code column number if you want
}
if (!sheetTabName) {//The sheet tab name was not passed in to the function
sheetTabName = "Formularantworten 2";//Hard code if needed
}
//end of user settings
ss = SpreadsheetApp.getActiveSpreadsheet();//Get the active spreadsheet - this code must be in a project bound to spreadsheet
sh = ss.getSheetByName(sheetTabName);
lastRow = sh.getLastRow();
lastColumn = sh.getLastColumn();
Logger.log('lastRow: ' + lastRow)
rowOfDataJustSaved = sh.getRange(lastRow, 1, 1, lastColumn).getValues();//Get the values that were just saved
valueToSearchFor = rowOfDataJustSaved[0][columnWithUniqueIdentifier-1];
Logger.log('valueToSearchFor: ' + valueToSearchFor)
dataFromColumnToMatch = sh.getRange(1, columnWithUniqueIdentifier, lastRow-1, 1).getValues();
dataFromColumnToMatch = dataFromColumnToMatch.toString().split(",");
Logger.log('dataFromColumnToMatch: ' + dataFromColumnToMatch)
rowWithExistingUniqueValue = dataFromColumnToMatch.indexOf(valueToSearchFor);
Logger.log('rowWithExistingUniqueValue: ' + rowWithExistingUniqueValue)
if (rowWithExistingUniqueValue === -1) {//There is no existing data with the unique identifier
return;
}
sh.getRange(rowWithExistingUniqueValue + 1, 1, 1, rowOfDataJustSaved[0].length).setValues(rowOfDataJustSaved);
sh.deleteRow(lastRow);//delete the row that was at then end
SpreadsheetApp.getActiveSpreadsheet().toast("Updating Data Set Successful")
}
The Trigger will throw this Error Message:
23.11.2020, 10:27:03 Info lastRow: 7
23.11.2020, 10:27:03 Info valueToSearchFor: undefined
23.11.2020, 10:27:03 Fehler Exception: Konvertierung von "[object Object]" in int nicht möglich.
at updateExisting(Code:28:30)
GSheet_Trigger_Error_Messeage
Any idea of what I am doing wrong here?
Thanks so much in advance.
EDIT:
Here is a debugger log for rowofdatajustsaved & columnWithUniqueIdentifier.
Seems like they work as intended.
Debugger_Log_UpdateExisting
Problem solved: there has to be a trigger var in the var statement. I figured that there is an unnecessary if statement in the code as well and fixed it. Updated code below.
function updateExisting(trigger, columnWithUniqueIdentifier,sheetTabName) {
var dataFromColumnToMatch,lastColumn,lastRow,rowWithExistingUniqueValue,rowOfDataJustSaved,
sh,ss,valueToSearchFor;
Logger.log('columnWithUniqueIdentifier' + columnWithUniqueIdentifier)
// USER SETTINGS - if the values where not passed in to the function
columnWithUniqueIdentifier = 4;//Hard code column number if you want
Logger.log('sheetTabName' + sheetTabName)
if (!sheetTabName) {//The sheet tab name was not passed in to the function
sheetTabName = "Formularantworten 2";//Hard code if needed
}
//end of user settings
ss = SpreadsheetApp.getActiveSpreadsheet();//Get the active spreadsheet - this code must be in a project bound to spreadsheet
sh = ss.getSheetByName(sheetTabName);
lastRow = sh.getLastRow();
lastColumn = sh.getLastColumn();
Logger.log('lastRow: ' + lastRow)
rowOfDataJustSaved = sh.getRange(lastRow, 1, 1, lastColumn).getValues();//Get the values that were just saved
Logger.log(rowOfDataJustSaved)
debugger
valueToSearchFor = rowOfDataJustSaved[0][columnWithUniqueIdentifier-1];
Logger.log('valueToSearchFor: ' + valueToSearchFor)
dataFromColumnToMatch = sh.getRange(1, columnWithUniqueIdentifier, lastRow-1, 1).getValues();
dataFromColumnToMatch = dataFromColumnToMatch.toString().split(",");
Logger.log('dataFromColumnToMatch: ' + dataFromColumnToMatch)
rowWithExistingUniqueValue = dataFromColumnToMatch.indexOf(valueToSearchFor);
Logger.log('rowWithExistingUniqueValue: ' + rowWithExistingUniqueValue)
if (rowWithExistingUniqueValue === -1) {//There is no existing data with the unique identifier
return;
}
sh.getRange(rowWithExistingUniqueValue + 1, 1, 1, rowOfDataJustSaved[0].length).setValues(rowOfDataJustSaved);
sh.deleteRow(lastRow);//delete the row that was at then end
SpreadsheetApp.getActiveSpreadsheet().toast("Updating Data Set Successful")
}

<IPython.core.display.HTML object> instead of graph

I am trying to achieve the following Twitter-Visualization project in iPython: http://www.amypeniston.com/web/visualizing-twitter-data
For the last step, my code is:
%pylab
dogs = pd.read_csv(' C:/Users/Alex/mongodb/bin/outputTweets.csv')
dogs['created_at'] = pd.to_datetime(pd.Series(dogs['created_at']))
dogs.set_index('created_at', drop=False, inplace=True)
dogs.index = dogs.index.tz_localize('GMT').tz_convert('EST')
dogs.index = dogs.index - DateOffset(hours = 12)
dogs.index
dogs1m = dogs['created_at'].resample('1t', how='count')
v.core.initialize_notebook()
area = v.Area(dogs1m)
area.colors(brew='Spectral')
area.display()
However, all I get in return is:
IPython.core.display.HTML object

error when add multiple OBX segments to NHapi.Model.V25.Group.VXU_V04_ORDER

I am working on creating HL7 VXU V04 type message using NHapi V2.5.
Below is the required message outcome( from NIST site:http://hl7v2-iz-testing.nist.gov/mu-immunization/)
The issue I am running into is how to create four OBX segments("NHapi.Model.V25.Segment.OBX ") and add it to the "NHapi.Model.V25.Group.VXU_V04_ORDER" ?
Below is my code, Line#5 works, it create multiple ORDER but if i try to do the same to create multiple OBSERVATION (Line#8), I get the below error:
"Can't create repetition #1 of Structure OBSERVATION - this Structure is non-repeating"
As per HL7 specifications OBSERVATION is repeating structure, Anyone please help here?
Any pointers or any suggestions are greatly appreciated.
NHapi.Model.V25.Message.VXU_V04 vxuMsg = new VXU_V04();
PipeParser parser = new PipeParser();
for (int i = 0; i < person.Immunizations.Count; i++)
{
NHapi.Model.V25.Group.VXU_V04_ORDER orc = (NHapi.Model.V25.Group.VXU_V04_ORDER)vxuMsg.GetStructure("ORDER", i);
for (int j = 0; j < 2; j++)
{
NHapi.Model.V25.Group.VXU_V04_OBSERVATION observation = (NHapi.Model.V25.Group.VXU_V04_OBSERVATION)orc.GetStructure("OBSERVATION", j);
NHapi.Model.V25.Segment.OBX obx1 = (NHapi.Model.V25.Segment.OBX)obx.GetStructure("OBX");
}
NHapi.Model.V25.Segment.RXA im = orc.RXA;
NHapi.Model.V25.Segment.ORC oc = orc.ORC;
NHapi.Model.V25.Segment.RXR rxr = orc.RXR;
}
Required message outcome
MSH|^~\&|Test EHR Application|X68||NIST Test Iz Reg|201207010822||VXU^V04^VXU_V04|NIST-IZ-001.00|P|2.5.1|||AL|ER
PID|1||D26376273^^^NIST MPI^MR||Snow^Madelynn^Ainsley^^^^L|Lam^Morgan|20070706|F||2076-8^Native Hawaiian or Other Pacific Islander^CDCREC|32 Prescott Street Ave^^Warwick^MA^02452^USA^L||^PRN^PH^^^657^5558563|||||||||2186-5^non Hispanic or Latino^CDCREC
PD1|||||||||||02^Reminder/Recall - any method^HL70215|||||A|20120701|20120701
NK1|1|Lam^Morgan^^^^^L|MTH^Mother^HL70063|32 Prescott Street Ave^^Warwick^MA^02452^USA^L|^PRN^PH^^^657^5558563
ORC|RE||IZ-783274^NDA|||||||I-23432^Burden^Donna^A^^^^^NIST-AA-1||57422^RADON^NICHOLAS^^^^^^NIST-AA-1^L
RXA|0|1|20120814||140^Influenza, seasonal, injectable, preservative free^CVX|0.5|mL^MilliLiter [SI Volume Units]^UCUM||00^New immunization record^NIP001|7832-1^Lemon^Mike^A^^^^^NIST-AA-1|^^^X68||||Z0860BB|20121104|CSL^CSL Behring^MVX|||CP|A
RXR|C28161^Intramuscular^NCIT|LD^Left Arm^HL70163
OBX|1|CE|64994-7^Vaccine funding program eligibility category^LN|1|V05^VFC eligible - Federally Qualified Health Center Patient (under-insured)^HL70064||||||F|||20120701|||VXC40^Eligibility captured at the immunization level^CDCPHINVS
OBX|2|CE|30956-7^vaccine type^LN|2|88^Influenza, unspecified formulation^CVX||||||F
OBX|3|TS|29768-9^Date vaccine information statement published^LN|2|20120702||||||F
OBX|4|TS|29769-7^Date vaccine information statement presented^LN|2|20120814||||||F
Dim vxuMsg As NHapi.Model.V25.Message.VXU_V04 = New VXU_V04()
Dim orc As NHapi.Model.V25.Group.VXU_V04_ORDER = DirectCast(vxuMsg.GetStructure("ORDER", 0), NHapi.Model.V25.Group.VXU_V04_ORDER)
Dim observation As NHapi.Model.V25.Group.VXU_V04_OBSERVATION = orc.GetOBSERVATION(0) 'DirectCast(orc.GetStructure("OBSERVATION", 0), NHapi.Model.V25.Group.VXU_V04_OBSERVATION)
Dim orderobservation As VXU_V04_ORDER = vxuMsg.GetORDER(0)
Dim obx1 As NHapi.Model.V25.Segment.OBX = DirectCast(observation.GetStructure("OBX"), NHapi.Model.V25.Segment.OBX)
obx1 = orderobservation.GetOBSERVATION(0).OBX
obx1.SetIDOBX.Value = "1"
obx1.ValueType.Value = "CE"
obx1.ObservationIdentifier.Identifier.Value = "64994-7"
obx1.ObservationIdentifier.Text.Value = "Vaccine funding program eligibility category"
obx1.ObservationIdentifier.NameOfCodingSystem.Value = "LN"
obx1.ObservationSubID.Value = "1"
Dim ce As New CE(oru01)
ce.Identifier.Value = "V05"
ce.Text.Value = "VFC eligible - Federally Qualified Health Center Patient(under-insured)"
ce.NameOfCodingSystem.Value = "HL70064"
obx1.GetObservationValue(0).Data = ce
obx1.ObservationResultStatus.Value = "F"
obx1.DateTimeOfTheObservation.Time.Value = "20120701"
obx1.GetObservationMethod(0).Identifier.Value = "VXC40"
obx1.GetObservationMethod(0).Text.Value = "Eligibility captured at the immunization level"
obx1.GetObservationMethod(0).NameOfCodingSystem.Value = "CDCPHINVS"
Dim obx2 As NHapi.Model.V25.Segment.OBX = obx1
obx2 = orderobservation.GetOBSERVATION(1).OBX
obx2.SetIDOBX.Value = "2"
obx2.ValueType.Value = "CE"
obx2.ObservationIdentifier.Identifier.Value = "30956-7"
obx2.ObservationIdentifier.Text.Value = "vaccine type"
obx2.ObservationIdentifier.NameOfCodingSystem.Value = "LN"
obx2.ObservationSubID.Value = "2"
Dim ce2 As New CE(oru01)
ce2.Identifier.Value = "88"
ce2.Text.Value = "Influenza, unspecified formulation"
ce2.NameOfCodingSystem.Value = "CVX"
obx2.GetObservationValue(0).Data = ce2
obx2.ObservationResultStatus.Value = "F"
Dim obx3 As NHapi.Model.V25.Segment.OBX = obx1 'DirectCast(observation.GetStructure("OBX"), NHapi.Model.V251.Segment.OBX)
obx3 = orderobservation.GetOBSERVATION(2).OBX
obx3.SetIDOBX.Value = "3"
obx3.ValueType.Value = "TS"
obx3.ObservationIdentifier.Identifier.Value = "29768-9"
obx3.ObservationIdentifier.Text.Value = "Date vaccine information statement published"
obx3.ObservationIdentifier.NameOfCodingSystem.Value = "LN"
obx3.ObservationSubID.Value = "2"
Dim ts3 As New TS(oru01)
ts3.Time.Value = "20120702"
obx3.GetObservationValue(0).Data = ts3
obx3.ObservationResultStatus.Value = "F"

How to copy one spreadsheet's cell to another spreadsheet

I tried coding like spreadsheet API batch copy https://developers.google.com/google-apps/spreadsheets/#updating_multiple_cells_with_a_batch_request, The sample is base on same spreadsheet, I added a target cell but always get same error
com.google.gdata.client.batch.BatchInterruptedException: Batch Interrupted (some operations might have succeeded) : a response has already been sent for batch operation update id='R1C1'
My code like this
SpreadsheetService spreadsheetService = getSpreadsheetService(currentEmail);
WorksheetFeed feed = spreadsheetService.getFeed(getWorksheetFeedURL(sourceId), WorksheetFeed.class);
SpreadsheetEntry targetFeed = spreadsheetService.getEntry(getSpreadsheetFeedURL(targetId), SpreadsheetEntry.class);
SpreadsheetEntry sourceFeed = spreadsheetService.getEntry(getSpreadsheetFeedURL(sourceId), SpreadsheetEntry.class);
for(WorksheetEntry entry:feed.getEntries()){
WorksheetEntry targetWorksheet = spreadsheetService.insert(targetFeed.getWorksheetFeedUrl(), entry);
FeedURLFactory urlFactory = FeedURLFactory.getDefault();
URL cellFeedUrl = urlFactory.getCellFeedUrl(sourceFeed.getKey(), "od6", "private", "full");
URL targetFeedUrl = urlFactory.getCellFeedUrl(targetFeed.getKey(), "od6", "private", "full");
CellFeed cellFeed = spreadsheetService.getFeed(targetFeedUrl, CellFeed.class);
List<CellAddress> cellAddrs = new ArrayList<CellAddress>();
for (int row = 1; row <= entry.getRowCount(); ++row) {
for (int col = 1; col <= entry.getColCount(); ++col) {
cellAddrs.add(new CellAddress(row, col));
}
}
Map<String, CellEntry> cellEntries = getCellEntryMap(spreadsheetService, cellFeedUrl, cellAddrs);
CellFeed batchRequest = new CellFeed();
for (CellAddress cellAddr : cellAddrs) {
URL entryUrl = new URL(targetFeedUrl.toString() + "/" + cellAddr.idString);
CellEntry batchEntry = new CellEntry(cellAddr.row, cellAddr.col, cellAddr.idString);
String inputValue = cellEntries.get(cellAddr.idString).getCell().getInputValue();
batchEntry.changeInputValueLocal(inputValue);
batchEntry.setId(String.format("%s/%s", targetFeedUrl.toString(), cellAddr.idString));
System.out.println(targetFeedUrl.toString()+": "+cellAddr.idString+" "+ inputValue);
BatchUtils.setBatchId(batchEntry, cellAddr.idString);
BatchUtils.setBatchOperationType(batchEntry, BatchOperationType.UPDATE);
batchRequest.getEntries().add(batchEntry);
}
spreadsheetService.setHeader("If-Match", "*");
// Submit the update
Link batchLink = cellFeed.getLink(ILink.Rel.FEED_BATCH, ILink.Type.ATOM);
CellFeed batchResponse = spreadsheetService.batch(new URL(batchLink.getHref()), batchRequest);
boolean isSuccess = true;
for (CellEntry entry1 : batchResponse.getEntries()) {
String batchId = BatchUtils.getBatchId(entry);
if (!BatchUtils.isSuccess(entry1)) {
isSuccess = false;
BatchStatus status = BatchUtils.getBatchStatus(entry);
}
}
spreadsheetService.setHeader("If-Match", null);
Batch copy:
What is the fastest way to update a google spreadsheet with a lot of data through the spreadsheet api?
There is a Bug with cell references such as $A5.
They will not write to the spreadsheet. While both A5 and $A$5 work, references with just one $ in cause a problem. I forget the fine detail.

Resources