how to make pivot table using Xlwings? - xlwings

Would you let me know how to make the pivot table in excel using xlwings?
please give me the sample code
Thanks for your help
I have tried to find how to make it but I couldn't find it

Creating a PivotTable with xlwings is not currently straightforward, and requires the use of the .api to access the VBA functions.
An example to create a PivotTable using my mock data in a Table called Table1 of 3 columns of data with headers: "Colour", "Type", "Data".
# set the kwarg values for creating PivotTable
source_type = xw.constants.PivotTableSourceType.xlDatabase
source_data = wb.sheets["Sheet1"]["Table1[#All]"].api # cannot be of type Range or String
table_destination = wb.sheets["Sheet1"]["A20"].api # cannot be of type Range or String
table_name = "PTable1"
# create PivotTable
wb.api.PivotCaches().Create(SourceType=source_type,
SourceData=source_data).CreatePivotTable(
TableDestination=table_destination,
TableName=table_name)
pt = ws.api.PivotTables(table_name)
# Set Row Field (Rows) as Colour column of table
pt.PivotFields("Colour").Orientation = xw.constants.PivotFieldOrientation.xlRowField
# Set Column Field (Columns) as Type column of table
pt.PivotFields("Type").Orientation = xw.constants.PivotFieldOrientation.xlColumnField
# Set Data Field (Values) as Data
pt.AddDataField(pt.PivotFields("Data"),
# with name as "Sum of Data"
"Sum of Data",
# and calculation type as sum
xw.constants.ConsolidationFunction.xlSum)
Additional Detail
For reason of xlDatabase source_type, the VBA documentation can be found here
The parameters can be seen in the VBA documentation here. And this tutorial provides a detailed explanation of these, along with how to change this for different scenarios (dynamic range, in a new workbook, etc.); the guide gives a couple of additional changes to the formatting of the values, such as position of fields and number format.
The options for type of data calculation can be found here.

Related

Can I dynamically derive Dax Filters from "dissecting"a criteria field in my database?

I have a database table that contains records, where each record has a criteria attribute. This criteria attribute can hold anywhere between 1-n criteria that I'd like to apply as filters on a different table.
This looks something like:
message.status:::eq:::submitted;;;message.count:::ge:::5
but could also be only
message.count:::ge:::5
What I'd like to do in DAX, is take that string and translate it into dynamic Filter attributes. So I somehow need to split the string based on ;;;, and then disect each section into the target (e.g. message[count]), the operator (e.g. ge --> >=) and the value (e.g. 5).
So in the end the following DAX snippet should be added to my Calculate 1 or more times:
example measure = CALCULATE(
COUNTROWS('message),
FILTER (
ALL('message'),
--- line below should be dynamically injected
message[count] >= 5
),
I'm struggling with how to create a loop (is this even possible in PBI?), and then even with a single string... hoe to filter based on this.
Thanks
You can try to build new table for splited message.
Table 2 =
var _splitby = ";;;"
var _string = SELECTCOLUMNS(ADDCOLUMNS(VALUES('Table'[message]),"pathx", SUBSTITUTE([message],_splitby,"|")),"pathx",[pathx])
var _generate = GENERATE(_string, GENERATESERIES(1, PATHLENGTH([pathx])))
var _GetVal = SELECTCOLUMNS(_generate, "Msg", PATHITEM([pathx], [Value]))
return
_GetVal
If you have always message.count:::ge::: like string at the end, you can follow these steps in Power Query-
Step 1: Duplicate you message column
Step-2: apply split on new duplicated column using string message.count:::ge::: and you will have a new column with last Numeric value from your original text.
Step-3: you can now apply filter on the new column.
Sample Output-

How to add a list of "permitted values" to a parameter by using a BigQuery connector in Data Studio?

I was wondering if there is a way to add a list of "permitted values" to a parameter in Data Studio by using a custom query / BigQuery connector?
There is an option to do it manually in the Data Studio UI:
Permitted values through Data Studio UI
But I am looking for a solution to do it through SQL because I have to pass a long list of values that can be changed every day, so adding a list of values manually through the UI is impossible.
Is it possible to do it through a custom query?
Thank you!
You do not need a custom query to define allowed Values if you want to Filter for them just set them up as a Dimension and add a Filter Control with an drop-down List. This will allow you to select the present Values and filter for them.
Let me know if this solves it for you
You can add parameters to a custom SQL query in the connector, just like the following examples show
SELECT word FROM `TABLE` WHERE corpus = #corpus;
Use a string with contains and a number:
SELECT * FROM `bigquery-public-data.baseball.games_post_wide`
WHERE REGEXP_CONTAINS(gameId, #s)
AND attendance > #attendance LIMIT 100;
Use a multi-select string parameter. Note the use of UNNEST to flatten the list of values:
SELECT * from user.users as user WHERE display_name in UNNEST(#name);
Date parameter example:
SELECT creation_date, age, display_name from user.users as user
WHERE creation_date > PARSE_DATE('%Y%m%d', #DS_START_DATE)
AND creation_date < PARSE_DATE('%Y%m%d', #DS_END_DATE);
Email parameter example:
Select * from Sales WHERE sales-rep-email = #DS_USER_EMAIL;
Here you can read more about using parameters in Data Studio

How to add a new column with custom values, based on a WHERE clause from another table in PowerBi?

I am stuck while dynamically forming a new column based certain WHERE clause from another Table in PowerBi. To give more details, let's say I have a table with item numbers associated with a Customer Name. In another table, I have to add a new column, which will dynamically add the item numbers associated with a particular customer and append as a query parameter to a base url.
So, my first table looks like this:
The second table that I want is this:
The query parameter value in the URL, has to be dynamically based on a SELECT query with a WHERE clause and pick up the ItemNumbers using the Customer field which is common between both. So, how can this be done in PowerBi? Any help would be really appreciated :)
I have one table in my model "TableRol" if I want to summarize my Date as the string I can use CONCATENATEX;
URL = CONCATENATE(CONCATENATE("http:\\mysite.com\parametersHere\getitem?='",CONCATENATEX(VALUES('TableRol'[Date]), 'TableRol'[Date],";")),"'")

How do I create an If statement to classify a number between a range that is on another table?

I am trying to create a column in the "Data" section in powerbi, not power query. I have a 1 table that contains ID numbers and another table that contains the type of ID number with its given range that it needs to fall under. Each column is type "Text". The example below contains two columns
Below is the code I am working on
Answer = LOOKUPVALUE('Table 2'[Type],'Table 2'[Range],
IF(Contains('Table 2','Table 2'[Range],"-") = TRUE,
IF(AND('Table 1'[ID] >= Left('Table 2'[Range],"-"),
'Table 1'[ID] < Right('Table 2'[Range],"-")),
'Table 1'[ID],0),'Table 1'[ID]))
Below is an example I am trying to replicate:
What would be the best way to solve this problem?

TypeError: dataset must be a Dataset or a DatasetReference(GBQ)

I am trying to list out Datasets within a project and tables within a dataset,but unable to understand the meaning of TypeError: dataset must be a Dataset or a Dataset Reference
Code 1 : List datasets within a project
from google.cloud import bigquery
GBQ_client = bigquery.Client(project= config.PROJECT_ID)
print GBQ_client.list_datasets()
Output:
<google.api_core.page_iterator.HTTPIterator object at 0x000000000660ACF8>
Code 2 : List tables within a dataset
tables = GBQ_client.list_tables(dataset = config.Dataset_ID)
where config.Dataset_ID = 'projectId:xxxxxxx'
Output:
TypeError: dataset must be a Dataset or a DatasetReference
To list all datasets within your project you were close, you just need to iterate over the HTTPIterator now:
datasets = list(GBQ_client.list_datasets())
Now to iterate over tables you probably have several ways to do so. If you have a specific datasetId such as "dataset123" then one way you could do is:
dataset = [dataset for dataset in client.list_datasets() if dataset.dataset_id == 'dataset123'][0] # be careful, if empty this will break
tables = list(client.list_tables(dataset=dataset.reference))
And tables will be a list with items associated to each table you have in "dataset123".
If you know upfront the name of the table you can retrieve it directly:
table = dataset.table('your table name')
Notice that list_tables method expects either an object from bigquery.dataset.Dataset or bigquery.dataset.DatasetReference to work; as it seems, you used a string in config.dataset so it won't be accepted as input (notice I used dataset.reference as input for this method).