Converting Encoding UTF-8 to ANSI In PowerBuilder
Add PowerScript Create Global Function utf8_to_ansi
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | Global Type utf8_to_ansi From function_object End Type Type Prototypes Function ULong MultiByteToWideChar(ULong CodePage, ULong dwflags, Ref String lpmultibytestr, ULong cchmultibyte, Ref Blob lpwidecharstr, ULong cchwidechar) Library "kernel32.dll" Function ULong WideCharToMultiByte(ULong CodePage, ULong dwflags, Ref Blob lpwidecharstr, ULong cchwidechar, Ref String lpmultibytestr, ULong cbMultiByte, Ref String lpUsedDefaultChar, Ref Boolean lpUsedDefaultChar) Library "kernel32.dll" End Prototypes Forward Prototypes Global Function String utf8_to_ansi (String as_utf8) End Prototypes Global Function String utf8_to_ansi (String as_utf8); //convert utf-8 -> ansi //use a wide-char native string as pivot Constant ULong CP_ACP = 0 Constant ULong CP_UTF8 = 65001 String ls_wide, ls_ansi, ls_null Blob lbl_wide ULong ul_len Boolean lb_flag SetNull(ls_null) lb_flag = False //get utf-8 string length converted as wide-char SetNull(lbl_wide) ul_len = multibytetowidechar(CP_UTF8, 0, as_utf8, -1, lbl_wide, 0) //allocate buffer to let windows write into ls_wide = Space(ul_len * 2) lbl_wide = Blob(ls_wide) //convert utf-8 -> wide char ul_len = multibytetowidechar(CP_UTF8, 0, as_utf8, -1, lbl_wide, ul_len) //get the final ansi string length SetNull(ls_ansi) ul_len = widechartomultibyte(CP_ACP, 0, lbl_wide, -1, ls_ansi, 0, ls_null, lb_flag) //allocate buffer to let windows write into ls_ansi = Space(ul_len) //convert wide-char -> ansi ul_len = widechartomultibyte(CP_ACP, 0, lbl_wide, -1, ls_ansi, ul_len, ls_null, lb_flag) Return ls_ansi End Function |
Read data from file and encoding utf8 to ansi then import to dw_tab datawindow. (Import data to DataWindow/Datastore)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | //Read data from file and encoding utf8 to ansi then import to dw_tab datawindow String ls_path, ls_file, ls_chunk, ls_ansi ls_path = sle_path.Text Int li_file If Not FileExists(ls_path) Then Return li_file = FileOpen(ls_path, streammode!) If li_file > 0 Then FileSeek(li_file, 3, FromBeginning!) //skip the utf-8 BOM //read the file by blocks, FileRead is limited to 32kB Do While FileRead(li_file, ls_chunk) > 0 ls_file += ls_chunk //concatenate in loop works but is not so performant Loop FileClose(li_file) ls_ansi = utf8_to_ansi(ls_file) dw_tab.ImportString( Text!, ls_ansi) End If |
Good Luck!