How to change encoding from UTF-8 to UTF-8-BOM of exported *.txt files from Excel?

落花浮王杯 提交于 2021-02-11 18:19:39

问题


Exported text files from Excel are encoded with UTF-8.

An encoding UTF-8-BOM is needed.

I think that in code shall be inserted a row, written like:

Java

?xml version="1.0" encoding="UTF-8"?

Jasperreport CSV UTF-8 without BOM instead of UTF-8

or

HTML5

meta charset="utf-8"

Bad UTF-8 without BOM encoding

Sub export_data()
Dim row, column, i, j As Integer
Dim fullPath, myFile As String

fullPath = "C:\Workspace"
row = 21
column = 5

For i = 1 To column
    myFile = Cells(1, i).Value + ".txt"
    myFile = fullPath + "/" + myFile
    Open myFile For Output As #1
    For j = 2 To row
        Print #1, Cells(j, i).Value
    Next j
    Close #1
Next i

End Sub

How can I define and where to put a row, which defines encoding UTF-8-BOM? Thank You.


回答1:


Instead of Printing the file line by line, it might be more efficient to

  • save your selected range as a CSV UTF-8
    • you might need to change the file type after saving
  • Use ADO to process the file as UTF-8

Either will add a BOM automatically.

EDIT

If you are unfamiliar, you could perform the save to csv - utf8 process manually with the macro recorder turned on. Then examine what you have recorded and make appropriate edits.

Another way of adding the BOM, in the context of your existing code, would be to write it directly as a byte array to the first line.

For example:

Dim BOM(0 To 2) As Byte 'EF BB BF
    BOM(0) = &HEF
    BOM(1) = &HBB
    BOM(2) = &HBF

Open myFile For Binary Access Write As #1
    Put #1, 1, BOM
Close #1

will put the BOM at the beginning of the file. You should then change the mode in your subsequent Print code to Append.

I suggest you read about the pros and cons of using Print vs Write

You should also read about declaration statements. In yours, only the last variable on each line is being declared as the specified type; the preceding variables are being implicitly declared as being of type Variant.



来源:https://stackoverflow.com/questions/54168403/how-to-change-encoding-from-utf-8-to-utf-8-bom-of-exported-txt-files-from-exce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!