Экспорт таблиц данных из Spotfire в CSV с помощью скрипта IronPython

У меня есть скрипт IronPython, который я использую для экспорта всех моих таблиц данных из проекта Spotfire.

В настоящее время работает отлично. Он просматривает все таблицы данных и экспортирует их как «.xlsx». Теперь мне нужно экспортировать файлы как «.csv», что, как я думал, будет так же просто, как изменить «.xlsx» на «.csv».

Этот сценарий по-прежнему экспортирует файлы, называет их все .csv, но то, что находится внутри файла, - это .xlsx, я не знаю, как и почему. Код просто меняет имя расширения файла, но не конвертирует файл в csv.

Вот код, который я сейчас использую:

Я разместил полный код внизу, а код, который, по моему мнению, имеет отношение к моему вопросу, в отдельном блоке кода вверху.

if(dialogResult == DialogResult.Yes):
    for d in tableList: #cycles through the table list elements defined above
        writer = Document.Data.CreateDataWriter(DataWriterTypeIdentifiers.ExcelXlsDataWriter)
        table =  Document.Data.Tables[d[0]] #d[0] is the Data Table name in the Spotfire project (defined above)
        filtered = Document.ActiveFilteringSelectionReference.GetSelection(table).AsIndexSet() #OR pass the filter
        stream = File.OpenWrite(savePath+'\\'+ d[1] +".csv") #d[1] is the Excel alias name. You could also use d.Name to export with the Data Table name
        names = []
        for col in table.Columns: 
            names.append(col.Name)
        writer.Write(stream, table, filtered, names)
        stream.Close()

Я думаю, это может быть связано с ExcelXlsDataWriter. Я тоже пробовал с ExcelXlsxDataWriter. Есть ли csv-писатель, который я мог бы использовать для этого? Я считаю, что файлы csv и txt имеют другой писатель.

Любая помощь приветствуется.

Полный сценарий показан ниже:

import System
import clr
import sys

clr.AddReference("System.Windows.Forms")
from sys import exit
from System.Windows.Forms import FolderBrowserDialog, MessageBox, MessageBoxButtons, DialogResult
from Spotfire.Dxp.Data.Export import DataWriterTypeIdentifiers
from System.IO import File, FileStream, FileMode

#This is a list of Data Tables and their Excel file names. You can see each referenced below as d[0] and d[1] respectively.
tableList = [
            ["TestTable1"],
            ["TestTable2"],
            ]

#imports the location of the file so that there is a default place to put the exports.
from Spotfire.Dxp.Application import DocumentMetadata
dmd = Application.DocumentMetadata #Get MetaData
path = str(dmd.LoadedFromFileName) #Get Path
savePath = '\\'.join(path.split('\\')[0:-1]) + "\\DataExports\\"

dialogResult = MessageBox.Show("The files will be save to "+savePath
                +". Do you want to change location?"
                , "Select the save location", MessageBoxButtons.YesNo)
if(dialogResult == DialogResult.Yes):
    # GETS THE FILE PATH FROM THE USER THROUGH A FILE DIALOG instead of using the file location
    SaveFile = FolderBrowserDialog()
    SaveFile.ShowDialog()
    savePath = SaveFile.SelectedPath

#message making sure that the user wants to exporthe files.
dialogResult = MessageBox.Show("Export Files."
                                +"  Export Files","Are you sure?", MessageBoxButtons.YesNo)
if(dialogResult == DialogResult.Yes):
    for d in tableList: #cycles through the table list elements defined above
        writer = Document.Data.CreateDataWriter(DataWriterTypeIdentifiers.ExcelXlsDataWriter)
        table =  Document.Data.Tables[d[0]] #d[0] is the Data Table name in the Spotfire project (defined above)
        filtered = Document.ActiveFilteringSelectionReference.GetSelection(table).AsIndexSet() #OR pass the filter
        stream = File.OpenWrite(savePath+'\\'+ d[1] +".csv") #d[1] is the Excel alias name. You could also use d.Name to export with the Data Table name
        names = []
        for col in table.Columns: 
            names.append(col.Name)
        writer.Write(stream, table, filtered, names)
        stream.Close()

#if the user doesn't want to export then he just gets a message
else:
    dialogResult = MessageBox.Show("ok.")

person brandog    schedule 10.08.2016    source источник


Ответы (1)


По какой-то причине реализация Spotfire Iron Python не поддерживает пакет csv, реализованный на Python.

Обходной путь, который я нашел для вашей реализации, использует StdfDataWriter вместо ExcelXsDataWriter. Формат данных STDF - это формат текстовых данных Spotfire. Класс DataWriter в Spotfire поддерживает только Excel и STDF (см. здесь), а STDF ближе всего к CSV.

from System.IO import File
from Spotfire.Dxp.Data.Export import DataWriterTypeIdentifiers

writer = Document.Data.CreateDataWriter(DataWriterTypeIdentifiers.StdfDataWriter)
table = Document.Data.Tables['DropDownSelectors']
filtered = Document.ActiveFilteringSelectionReference.GetSelection(table).AsIndexSet()
stream = File.OpenWrite("C:\Users\KLM68651\Documents\dropdownexport.stdf")
names =[]
for col in table.Columns:
    names.append(col.Name)
writer.Write(stream, table, filtered, names)
stream.Close()

Надеюсь это поможет

person k88    schedule 10.08.2016
comment
Спасибо, это облом, что spotfire не экспортирует как .csv. STDF экспортирует быстро, но тогда мне пришлось бы пройти через какую-то пакетную обработку, чтобы преобразовать в CSV. Что у меня уже есть дело с xlsx .... Еще раз спасибо. - person brandog; 11.08.2016
comment
@brandog У них есть такая возможность, вы можете проверить ее здесь: community.tibco.com/wiki/ - person Tarun Parmar; 14.02.2020