# Get dataset from a tag query in PowerTable

**URL:** <https://forum.inductiveautomation.com/t/get-dataset-from-a-tag-query-in-powertable/77755>\
**Category:** Ignition\
**Tags:** perspective\
**Created:** [August 11, 2023, 12:58pm UTC](https://forum.inductiveautomation.com/t/get-dataset-from-a-tag-query-in-powertable/77755 "2023-08-11T12:58:05Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![italogustavoaraujo](https://sea1.discourse-cdn.com/inductiveautomation/user_avatar/forum.inductiveautomation.com/italogustavoaraujo/32/55235_2.png) [@italogustavoaraujo](https://forum.inductiveautomation.com/u/italogustavoaraujo)\
**Post date:** [August 11, 2023, 12:58pm UTC](https://forum.inductiveautomation.com/t/get-dataset-from-a-tag-query-in-powertable/77755/1 "2023-08-11T12:58:05Z")

</div>

Hello everyone, I have a PowerTable and I would like to get its dataset so I can format and export it in excel, because the native option only exports in CSV, and I didn't find any more options in the menu.

 ![image](https://us1.discourse-cdn.com/inductiveautomation/original/3X/a/7/a757929e13af03e86394dbb5c1960f1f6f3d111e.png)

---

<div class="post-metadata">

**Author:** ![pturmel](https://sea1.discourse-cdn.com/inductiveautomation/user_avatar/forum.inductiveautomation.com/pturmel/32/3295_2.png) [@pturmel](https://forum.inductiveautomation.com/u/pturmel)\
**Post date:** [August 11, 2023, 1:02pm UTC](https://forum.inductiveautomation.com/t/get-dataset-from-a-tag-query-in-powertable/77755/2 "2023-08-11T13:02:13Z")

</div>

You would run your own historian query with the corresponding settings and convert that to your target format.

---

<div class="post-metadata">

**Author:** ![paul-griffith](https://sea1.discourse-cdn.com/inductiveautomation/user_avatar/forum.inductiveautomation.com/paul-griffith/32/37249_2.png) [@paul-griffith](https://forum.inductiveautomation.com/u/paul-griffith)\
**Post date:** [August 11, 2023, 1:39pm UTC](https://forum.inductiveautomation.com/t/get-dataset-from-a-tag-query-in-powertable/77755/3 "2023-08-11T13:39:55Z")

</div>

You should be doing this anyways, in my opinion, because a chart should always be on a more efficient sampling rate for performance, and an export can be made to use a higher sample rate or natural return.

I think it's an antipattern the charts make it so tempting to directly export their data, but what do I know...

---

<div class="post-metadata">

**Author:** ![pturmel](https://sea1.discourse-cdn.com/inductiveautomation/user_avatar/forum.inductiveautomation.com/pturmel/32/3295_2.png) [@pturmel](https://forum.inductiveautomation.com/u/pturmel)\
**Post date:** [August 11, 2023, 1:42pm UTC](https://forum.inductiveautomation.com/t/get-dataset-from-a-tag-query-in-powertable/77755/4 "2023-08-11T13:42:16Z")

</div>

> [@paul-griffith](#):
>
> make it so tempting

Trying to be feature-comparable to Vision. Vision can handle high-resolution datasets and therefore exporting from the chart itself is perfectly reasonable. Perspective, not so much.

---

<div class="post-metadata">

**Author:** ![italogustavoaraujo](https://sea1.discourse-cdn.com/inductiveautomation/user_avatar/forum.inductiveautomation.com/italogustavoaraujo/32/55235_2.png) [@italogustavoaraujo](https://forum.inductiveautomation.com/u/italogustavoaraujo)\
**Post date:** [August 11, 2023, 5:22pm UTC](https://forum.inductiveautomation.com/t/get-dataset-from-a-tag-query-in-powertable/77755/5 "2023-08-11T17:22:37Z")

</div>

To solve it, I created the following code:

```auto
	pens = value['pens']
	startDate = value['startDate']
	endDate = value['endDate']
	
	# Número de resultados que você deseja trazer
	num_results = 50
	
	# Lista para armazenar os dados das tags
	dados_das_tags = {}
	
	# Loop através dos objetos na lista e buscar os dados
	for objeto in pens:
	    if "data" in objeto and "source" in objeto["data"]:
	        caminho_da_tag = objeto["data"]["source"]
	        
	        # Verifica se o caminho da tag está presente
	        if caminho_da_tag:
	            tag_path_parts = caminho_da_tag.split(":")
	            if len(tag_path_parts) > 2:
	                tag_name = tag_path_parts[-1] # Pega o nome da tag após "tag:"
	                
	                historico_da_tag = system.tag.queryTagHistory(
	                    paths=[caminho_da_tag],
	                    startDate=startDate,
	                    endDate=endDate,
	                    returnSize=num_results, # Especifica o número de resultados desejado
	                    aggregationMode="LastValue", # Modo de agregação LastValue
	                    returnFormat='Wide' # Formato de retorno amplo
	                )
	                
	                # Lista para armazenar os valores desta tag
	                valores_da_tag = []
	                
	                # Loop para obter os valores
	                for i in range(historico_da_tag.getRowCount()):
	                    timestamp = historico_da_tag.getValueAt(i, "t_stamp")
	                    valor = historico_da_tag.getValueAt(i, tag_name) # Obtém o valor da coluna correspondente ao nome da tag
	                    timestamp_str = system.date.format(timestamp, "dd/MM/yyyy HH:mm:ss")
	                    
	                    valor_formatado = "{:.2f}".format(round(valor, 2)) # Formata o valor com duas casas decimais
	                    valores_da_tag.append([timestamp_str, valor_formatado])
	                   
	                
	                dados_das_tags[tag_name] = valores_da_tag
	            else:
	                dados_das_tags[tag_name] = []
	        else:
	            dados_das_tags[tag_name] = []
	    else:
	        dados_das_tags[objeto["name"]] = []
	
	# Construir um novo dataset vazio com as colunas desejadas
	headers = ["time"]
	for tag_name in dados_das_tags.keys():
	    headers.append(tag_name)
	combined_dataset = system.dataset.toDataSet(headers, [])
	
	# Preencher o dataset combinado com os dados dos datasets individuais
	for i in range(num_results):
	    row = []
	    row.append(dados_das_tags[list(dados_das_tags.keys())[0]][i][0]) # Adicione a coluna de tempo
	    for tag_name in list(dados_das_tags.keys()):
	        if len(dados_das_tags[tag_name]) > i:
	            row.append(dados_das_tags[tag_name][i][1])
	        else:
	            row.append(None)
	    combined_dataset = system.dataset.addRow(combined_dataset, row)
	
	return combined_dataset

```

Now just export to excel.  
Thanks!
