Search code examples
excelcsvcomx++dynamics-ax-2012

X++ SysExcelWorkbook.saveAs - change encoding


I'm trying to convert XLS to CSV using job in AX2012. I have some non-ASCII characters in my XLS and I need to find out how can I set SysExcelWorkbook.saveAs method to use specific encoding (eg. UTF-8).

static void ExcelToCsv(Args _args)
{
    SysExcelApplication application;
    SysExcelWorkbooks   workbooks;
    SysExcelWorkbook    workbook;
    FileName            xlsFile, csvFile;
    ;

    application = SysExcelApplication::construct();
    application.displayAlerts(false);
    workbooks = application.workbooks();

    xlsFile = @"C:\test.xlsx";
    csvFile = @"C:\result.csv";

    workbooks.open(xlsFile);
    workbook = workbooks.item(1);

    workbook.saveAs(csvFile, 6);
    // workbook.saveAs(resFile, 22);
    // workbook.saveAs(resFile, 23);
    // workbook.saveAs(resFile, 24);
    application.quit();
}

The code above generates CSV, but all non-ASCII characters are not displaying property when opening in text editor. I expect that I will be able to choose encoding for my CSV file programmatically or use source (XSL) encoding. Is there a way to achieve this with X++?


Solution

  • I don't think you can do this without some workarounds as it appears to be an Excel limitation. It's do-able though if you really need it.

    It uses the Excel COM object to do the work, and you can see the reference here, where I can't find any options to specify encoding: https://learn.microsoft.com/en-us/office/vba/api/excel.workbook.saveas

    Here is the same issue, albeit in Powershell instead of X++ with solution (I think) being to export to UnicodeText instead of CSV, then replacing \t with , in the output file.

    It looks like you could output to UnicodeText by making the below change to your code, then you could just use some other string-replace to update the final file.

    #Excel
    // workbook.saveAs(csvFile, 6); // 6 == #xlCSV
    workbook.saveAs(csvFile, #xlUnicodeText);
    

    I'm not sure if this truly fixes your encoding issue without testing. I'd also want to double-check how single/double quotes are handled.