본문 바로가기
Data Analysis/Spotfire

[Spotfire Q&A] cross table (2개 이상)을 한번에 export 하기

by 불탄오징어 2021. 4. 4.
반응형

 

 

 

 

4월 3일에 아래와 같은 질문을 주신 것이 있어서 간단하게 답변 포스트를 작성했습니다.

 

 

 

사실 일전에 비슷한 질문을  주신 분이 계신데 제가 링크만드리고 이후에는 까먹고 있었던지라...죄송합니다. 일단 링크 상의 함수를 활용해서 간단하게 앞뒤로 소스를 추가했습니다. 동작 방식에 대해서 설명을 간략하게 드리면 

 

  • 현재 활성화 된 Page를 찾는다.(스크립트 실행 페이지)
  • Page내에서 Visualization을 찾고 그 중 Cross Table을 찾는다.
  • 해당 Cross Table의 내용을 Export 한다.

 

활성화된 Page 내에서 Cross Table이 있으면 모두 Export 합니다. Cross Table 명을 file명으로 하여 생성하니 동일한 명칭이 되지 않게 개별적으로 사전에 수정을 합니다. 소스는 다음과 같습니다.

 

from System.IO import *
from Spotfire.Dxp.Application.Visuals import VisualContent, VisualTypeIdentifiers

#----------------------------------------------------
# Export 용 함수 생성
def exportCrossTbl(vis,filename):
	vc = vis.As[VisualContent]()  #Visuals = Script parameter for Table/Cross Table visualization
	memStream = MemoryStream();
	sWriter = StreamWriter(memStream);

	#Exporting the data to Memory Stream
	vc.ExportText(sWriter);  #exports data in tab separated text
	sReader = StreamReader(memStream);
	memStream.Seek(0, SeekOrigin.Begin);	
	f=open(filename,"w")
	counter=0
	j=0
	str1=''

	while (sReader.Peek()>=0):
		line=[]
		counter=counter+1 #counts the number of rows in dataset
		a=sReader.ReadLine()
		lines=a.split("\t")
		for elem in lines:
			j=j+1 # counts the number of columns in dataset
			print elem
			if str(elem).find(",")<>-1:
				elem='"'+elem+'"'  # escaping comma already present in string
			line.append(elem)
		str1 = ','.join(str(e) for e in line)
		f.write(str1+'\n')
	f.close();
	MemoryStream.Dispose(memStream);
	sReader.Close()

#----------------------------------------------------
# 현재 ActivePage 확인
activeVisual = Document.ActivePageReference.ActiveVisualReference

# Export 할 경로(필요한 경우 수정)
filepath = "C:\\temp\\"

# 현재 ActivePage의 Visualization을 모두 가져옴
for visual in Document.ActivePageReference.Visuals:

	# Cross Table인 경우만 Export 수행
	if visual.TypeId.Name == 'Spotfire.CrossTable' :
		filename = filepath + visual.Title + ".csv"	# Cross Table명을 파일명으로 생성	
		exportCrossTbl(visual, filename)

       

 

 

샘플 파일도 첨부합니다. :)

 

sample_20210404.dxp
0.09MB

 

 

저장할 파일 경로를 별도지정(with Window Form)


오우... 저도 답글 주신 분 덕분에 배웠습니다.

 

from System.IO import *
from Spotfire.Dxp.Application.Visuals import VisualContent, VisualTypeIdentifiers
import System
from System.IO import FileStream, FileMode
from Spotfire.Dxp.Application.Visuals import TablePlot
from Spotfire.Dxp.Data.Export import DataWriterTypeIdentifiers
import clr
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import SaveFileDialog

#----------------------------------------------------
# Export 용 함수 생성
def exportCrossTbl(vis,filename):
	vc = vis.As[VisualContent]()  #Visuals = Script parameter for Table/Cross Table visualization
	memStream = MemoryStream();
	sWriter = StreamWriter(memStream);

	#Exporting the data to Memory Stream
	vc.ExportText(sWriter);  #exports data in tab separated text
	sReader = StreamReader(memStream);
	memStream.Seek(0, SeekOrigin.Begin);	
	f=open(filename,"w")
	counter=0
	j=0
	str1=''

	while (sReader.Peek()>=0):
		line=[]
		counter=counter+1 #counts the number of rows in dataset
		a=sReader.ReadLine()
		lines=a.split("\t")
		for elem in lines:
			j=j+1 # counts the number of columns in dataset
			print elem
			if str(elem).find(",")<>-1:
				elem='"'+elem+'"'  # escaping comma already present in string
			line.append(elem)
		str1 = ','.join(str(e) for e in line)
		f.write(str1+'\n')
	f.close();
	MemoryStream.Dispose(memStream);
	sReader.Close()

#----------------------------------------------------
# 현재 ActivePage 확인
activeVisual = Document.ActivePageReference.ActiveVisualReference

# Export 할 경로
filepath = "C:\\temp\\"

# 현재 ActivePage의 Visualization을 모두 가져옴
for visual in Document.ActivePageReference.Visuals:

	# Cross Table인 경우만 Export 수행
	if visual.TypeId.Name == 'Spotfire.CrossTable' :

		SaveFile = SaveFileDialog()
		SaveFile.Filter = "Excel Workbook (*.xls)|*.xls"
		SaveFile.ShowDialog()
		saveFilename = SaveFile.FileName

		exportCrossTbl(visual, saveFilename)     

 

스크립트를 위와 같이 수정하게 되면 Export 할 테이블 마다 저장경로와 파일명을 지정할 수 있도록 Form이 뜹니다.

 

 

댓글