【问题标题】:Converting xls to csv using VBScript and separate by semicolons使用 VBScript 将 xls 转换为 csv 并用分号分隔
【发布时间】:2012-03-02 06:44:55
【问题描述】:

我有一个 VBScript 代码 sn-p 将我的 xls 和 xlsx 文件转换为 csv 文件。但是,我希望每个单元格用分号而不是逗号分隔。在我的电脑上,列表分隔符设置为分号而不是逗号,所以当我打开一个 excel 窗口并保存为 csv 时,它用分号分隔。但是,我的 VBScript 会生成一个用逗号分隔的 csv 文件。我在网上找到了代码 sn-p,因为我不太了解 VBScript(我主要是一名 Java 程序员)。如何更改代码 sn-p 以用分号而不是逗号分隔 csv 文件?

if WScript.Arguments.Count < 2 Then
WScript.Echo "Error! Please specify the source path and the destination. Usage: XlsToCsv SourcePath.xls Destination.csv"
Wscript.Quit
End If
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
Dim oBook
Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(0))
oBook.SaveAs WScript.Arguments.Item(1), 6
oBook.Close False
oExcel.Quit
WScript.Echo "Done"

【问题讨论】:

    标签: csv vbscript xls xlsx


    【解决方案1】:

    你可以保留你原来的脚本,只需要给一个参数表明本地设置必须适用。这将我的 CSV 保存为 ;分隔符

    if WScript.Arguments.Count < 2 Then 
      WScript.Echo "Error! Please specify the source path and the destination. Usage: XlsToCsv SourcePath.xls Destination.csv" 
      Wscript.Quit 
    End If 
    Dim oExcel 
    Set oExcel = CreateObject("Excel.Application") 
    oExcel.DisplayAlerts = FALSE 'to avoid prompts
    Dim oBook, local
    Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(0))
    local = true 
    call oBook.SaveAs(WScript.Arguments.Item(1), 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, local) 'this changed
    oBook.Close False 
    oExcel.Quit 
    WScript.Echo "Done" 
    

    【讨论】:

      【解决方案2】:

      在分隔的文本文件中使用逗号可以在区域设置中找到它的根源。虽然逗号在美国是标准的,但德国等其他国家/地区使用分号。您可以在区域和语言设置中更改列表分隔符值,然后从 Excel 的另存为窗口中选择 CSV(逗号分隔)(.csv)。生成的文件将由系统设置中的任何值分隔。此脚本更改默认列表分隔符设置。然后它打开指定的电子表格并重新保存它。它在完成之前将系统设置恢复为之前的值。

      它接受两个命令行参数。第一个是输入电子表格;第二个是导出文件的输出文件名。

      strDelimiter = ";"
      
      strSystemDelimiter = ""           ' This will be used to store the current sytem value
      Const HKEY_CURRENT_USER = &H80000001
      
      ' Get the current List Separator (Regional Settings) from the registry
      strKeyPath = "Control Panel\International"
      strValueName = "sList"
      strComputer = "."
      Set objRegistry = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")
      objRegistry.GetStringValue HKEY_CURRENT_USER, strKeyPath, strValueName, strSystemDelimiter
      
      ' Set it temporarily to our custom delimiter
      objRegistry.SetStringValue HKEY_CURRENT_USER, strKeyPath, strValueName, strDelimiter
      
      ' Open spreadsheet with Excel and save it in a text delimited format
      Const xlCSV = 6
      
      Set objExcel = CreateObject("Excel.Application")
      Set objWorkbook = objExcel.Workbooks.Open(WScript.Arguments.Item(0))
      objWorkbook.SaveAs WScript.Arguments.Item(1), xlCSV
      objWorkbook.Close vbFalse         ' Prevent duplicate Save dialog
      objExcel.Quit
      
      ' Reset the system setting to its original value
      objRegistry.SetStringValue HKEY_CURRENT_USER, strKeyPath, strValueName, strSystemDelimiter
      

      经过一些测试,这似乎只能通过 Excel 的“另存为”对话框工作,而不是通过命令行或自动化。我稍微更改了脚本以使 Excel 窗口可见,并使用快捷键通过 Excel 界面打开“另存为”对话框。这应该可以解决问题。它在带有 Excel 2007 的 Vista x64 上对我有用。我希望这对你有用。

      strDelimiter = ";"
      
      strSystemDelimiter = ""           ' This will be used to store the current sytem value
      Const HKEY_CURRENT_USER = &H80000001
      
      ' Get the current List Separator (Regional Settings) from the registry
      strKeyPath = "Control Panel\International"
      strValueName = "sList"
      strComputer = "."
      Set objRegistry = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")
      objRegistry.GetStringValue HKEY_CURRENT_USER, strKeyPath, strValueName, strSystemDelimiter
      
      ' Set it temporarily to our custom delimiter
      objRegistry.SetStringValue HKEY_CURRENT_USER, strKeyPath, strValueName, strDelimiter
      
      ' Open spreadsheet with Excel and save it in a text delimited format
      Const xlCSV = 6
      
      Set objExcel = CreateObject("Excel.Application")
      objExcel.Visible = vbTrue
      Set objWorkbook = objExcel.Workbooks.Open(WScript.Arguments.Item(0))
      
      WScript.Sleep 500                 ' Delay to make sure the Excel workbook is open
      strWorkbookName = objExcel.ActiveWorkbook.Name
      strTitlebar = strWorkbookName
      Set WshShell = CreateObject("WScript.Shell")
      WshShell.AppActivate strTitlebar  ' Make the workbook active so it receives the keystrokes
      WshShell.SendKeys "%fa"           ' Keyboard shortcuts for the Save As dialog
      WScript.Sleep 500
      WshShell.SendKeys "%tc{ENTER}"    ' Change the Save As type to CSV
      If WScript.Arguments.Count > 1 Then
          WshShell.SendKeys "+{TAB}" & WScript.Arguments.Item(1)
          WScript.Sleep 500
      End If                            ' This If block changes the save name if one was provided
      WshShell.SendKeys "{ENTER}"       ' Save the file
      WScript.Sleep 500
      WshShell.SendKeys "{ENTER}"       ' Dismiss the CSV warning dialog
      Set WshShell = Nothing
      
      objWorkbook.Close vbFalse         ' Prevent duplicate Save dialog
      objExcel.Quit
      
      ' Reset the system setting to its original value
      objRegistry.SetStringValue HKEY_CURRENT_USER, strKeyPath, strValueName, strSystemDelimiter
      

      【讨论】:

      • 谢谢!但是,我在控制面板中将计算机上的分隔符更改为分号,但是当 VBScript 运行时,它使用逗号作为分隔符,这很奇怪,因为当我在 Excel 中另存为时,它用分号分隔。这似乎只是从命令行执行相同的操作,而不是单击并更改控制面板中的设置。但我会试试这个脚本,让你知道结果。
      • 是的,我得到了相同的结果。它用逗号分隔。我在学校计算机上,也许它不允许我编辑注册表项?当我在家用电脑上时,我会尝试。我希望这就是原因。我会在家里告诉你我的结果。
      • 卢克,我发现了问题并在我的回复中发布了一些新代码。这应该适合你。
      • 这也不起作用。 excel 文件打开,但随后代码尝试在 cmd 中使用命令“fatc”,并显示“这不是内部或批处理命令、可运行程序或批处理文件”。错误命令的常见错误消息。并且excel窗口也关闭了。我不确定为什么会发生此错误。但是,此解决方案可能对我不起作用,因为似乎会为我尝试转换的每个 excel 文件打开一个 excel 窗口,这是一个问题,因为我将使用它一次转换大约 700 个 excel 文件。 ..这是很多excel窗口。
      • 卢克,您使用的是什么版本的 Windows 和 Excel?它似乎没有激活 Excel 窗口。相反,击键被发送到恰好是命令外壳的当前活动窗口。此外,它将按顺序打开文件,因此您不应一次打开 700 个 excel 窗口。
      【解决方案3】:

      函数 SaveAs 是这样定义的: .SaveAs(FileName, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AccessMode, ConflictResolution, AddToMru, TextCodepage, TextVisualLayout, Local)

      也就是说,使用分号(如果您的区域语言选项设置正确)

      ExcelObj.Workbooks(1).SaveAs csvFile, 6,,,,,,,,,,True

      【讨论】:

      • 谢谢,但我不再需要此代码。不过非常感谢。
      • 这里的最佳答案...您唯一需要注意的是您的 Excel 版本 True on position 12 适用于 Excel 2013 对于 Excel 2010,它在位置 10 上少了 2 个参数一个也可以检查:msdn.microsoft.com/en-us/library/office/… 在那种情况下...
      【解决方案4】:

      您可以使用 FSO 对象重新打开文件,然后对逗号字符执行 Replace()。

      Const OpenAsDefault = -2
      Const FailIfNotExist = 0
      Const ForReading = 1
      Const ForWriting = 2
      
      Set oFSO = CreateObject("Scripting.FileSystemObject")
      Set fCSVFile = _
        oFSO.OpenTextFile("C:\path\file.csv", ForReading, FailIfNotExist, OpenAsDefault)
      
      sFileContents = fCSVFile.ReadAll
      fCSVFile.Close
      sFileContents = Replace(sFileContents, ",",";"))
      
      Set fCSVFile = oFSO.OpenTextFile("C:\path\file.csv", ForWriting, True)
      fCSVFile.Write(sFileContents)
      fCSVFile.Close
      

      【讨论】:

      • 这不是一个一致的解决方案,因为它还将替换文字中的逗号:John Doe,Euro,"1,234.00" 将解析为John Doe;Euro;"1;234.00",可能不是用户想要的。
      • 显然,如果这是数据类型,它就没有帮助。当我发布此内容时,没有其他回复,所以我只是提供一些回复。
      • 当然。如果用户只有一组有限的没有逗号的数据,它会正常工作。但是,将数据转换为正确的 CSV 文件是模棱两可的。甚至微软也跟不上rfc4180 格式的定义。
      • 是的,文件中会有钱,这就是我想用分号而不是逗号分隔的原因。如果我不处理金钱,我会坚持使用逗号并留在那里。但是感谢您的帮助,我很感激。
      【解决方案5】:

      我将参数更改为 true,并为我工作。

      if WScript.Arguments.Count < 2 Then
          WScript.Echo "Erro! Especifique origem e destino. Exemplo: XlsToCsv SourcePath.xls Destination.csv"
          Wscript.Quit
      End If
      Dim oExcel
      Set oExcel = CreateObject("Excel.Application")
      Dim oBook
      Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(0))
      call oBook.SaveAs(WScript.Arguments.Item(1), 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, true) --CHANGED
      oBook.Close False
      oExcel.Quit
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-09-18
        • 1970-01-01
        • 1970-01-01
        • 2011-01-29
        • 2018-04-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多