如何转换文件从csv与utf-8到csv使用vba

fkvaft9z  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(242)

我在SSIS中的脚本任务中使用下面的代码。代码的目的是将CSV文件(文件名以CO2开头)从UTF-8编码转换为标准CSV,然后将其加载到数据库表中。然而,代码没有按照预期转换文件。逻辑正确吗?感谢您的帮助。

Public Sub Main()

    ' Set the folder path where the files are located
    Dim folderPath As String
    folderPath = "<path>"

    ' Set the file extension you want to filter (assuming all are .csv)
    Dim fileExt As String
    fileExt = "*.csv"

    ' Set the initial file to process
    Dim fileName As String
    fileName = Dir(folderPath & "CO2 *" & fileExt)

    ' Loop through matching files
    Do While Len(fileName) > 0
        ' Construct the full file path
        Dim filePath As String
        filePath = folderPath & fileName

        ' Open the file, convert and overwrite
        ConvertAndOverwriteCSV(filePath)

        ' Get the next file
        fileName = Dir()

    Loop
    MsgBox("Conversion completed for CO2 files.")
End Sub

Sub ConvertAndOverwriteCSV(filePath As String)
    Dim oExcel
    oExcel = CreateObject("Excel.Application")

    ' Disable Excel UI elements
    oExcel.Visible = False
    oExcel.DisplayAlerts = False
    oExcel.AskToUpdateLinks = False
    oExcel.AlertBeforeOverwriting = False

    Dim oWorkbook As Object
    oWorkbook = oExcel.Workbooks.Open(filePath)
    oWorkbook.SaveAs(FileName:=filePath & oWorkbook.Name, FileFormat:=6)

End Sub

字符串

56lgkhnf

56lgkhnf1#

使用FileFormat:=6将生成一个UTF-8 CSV,开头带有BOM字符(请参见Byte Order Mark

  • my* 安装中的所有其他选项都将给予一个不带BOM的CSV(这将因其他人而异)。

尝试使用xlCSVMSDOS代替i.e. FileFormat:=24这里是从我的评论再次XlFileFormat enumeration的参考链接
如果您确定要转换为ANSI(我不相信你有,SSIS可以科普UTF-8文件),那么我相信你不能在Excel中使用SaveAs来实现这一点。即使xlTextMSDOS(21)也给出了UTF-8编码的文件。要转换为ANSI,你需要使用类似ADODB.Stream的对象(注意,FileSystemObject也能生成UTF-8)。这里有一个VB6/VBScript change file encoding to ansi的例子。

相关问题