Windows 在命令行上将XLS转换为CSV

Windows 在命令行上将XLS转换为CSV,windows,excel,csv,Windows,Excel,Csv,如何在windows命令行上将XLS文件转换为CSV文件 计算机已安装Microsoft Office 2000。如果无法使用Microsoft Office,我愿意安装OpenOffice。使用PowerShell如何 代码应该是这样的,但没有经过测试 $xlCSV = 6 $Excel = New-Object -Com Excel.Application $Excel.visible = $False $Excel.displayalerts=$False $WorkBook = $

如何在windows命令行上将XLS文件转换为CSV文件


计算机已安装Microsoft Office 2000。如果无法使用Microsoft Office,我愿意安装OpenOffice。

使用PowerShell如何

代码应该是这样的,但没有经过测试

$xlCSV = 6
$Excel = New-Object -Com Excel.Application 
$Excel.visible = $False 
$Excel.displayalerts=$False 
$WorkBook = $Excel.Workbooks.Open("YOUDOC.XLS") 
$Workbook.SaveAs("YOURDOC.csv",$xlCSV) 
$Excel.quit()
下面是一篇解释如何使用它的帖子


为什么不自己写呢

我从你的个人资料中看到,你至少有一些C#/.NET的经验。我会创建一个Windows控制台应用程序,并使用免费的Excel阅读器读取您的Excel文件。我已经使用了CodePlex中的available,没有任何问题(一件好事:这个阅读器不需要安装Excel)。您可以从命令行调用控制台应用程序


如果你发现自己被困在这里,我相信你会得到帮助。

Windows内置了一个Excel OLEDB数据提供程序;您可以使用它通过ADO.NET“查询”Excel工作表,并将结果写入CSV文件。需要少量编码,但您不需要在计算机上安装任何东西。

打开记事本,创建一个名为XlsToCsv.vbs的文件,然后将其粘贴到:

'* Usage: Drop .xl* files on me to export each sheet as CSV

'* Global Settings and Variables
Dim gSkip
Set args = Wscript.Arguments

For Each sFilename In args
    iErr = ExportExcelFileToCSV(sFilename)
    ' 0 for normal success
    ' 404 for file not found
    ' 10 for file skipped (or user abort if script returns 10)
Next

WScript.Quit(0)

Function ExportExcelFileToCSV(sFilename)
    '* Settings
    Dim oExcel, oFSO, oExcelFile
    Set oExcel = CreateObject("Excel.Application")
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    iCSV_Format = 6

    '* Set Up
    sExtension = oFSO.GetExtensionName(sFilename)
    if sExtension = "" then
        ExportExcelFileToCSV = 404
        Exit Function
    end if
    sTest = Mid(sExtension,1,2) '* first 2 letters of the extension, vb's missing a Like operator
    if not (sTest =  "xl") then
        if (PromptForSkip(sFilename,oExcel)) then
            ExportExcelFileToCSV = 10
            Exit Function
        end if
    End If
    sAbsoluteSource = oFSO.GetAbsolutePathName(sFilename)
    sAbsoluteDestination = Replace(sAbsoluteSource,sExtension,"{sheet}.csv")

    '* Do Work
    Set oExcelFile = oExcel.Workbooks.Open(sAbsoluteSource)
    For Each oSheet in oExcelFile.Sheets
        sThisDestination = Replace(sAbsoluteDestination,"{sheet}",oSheet.Name)
        oExcelFile.Sheets(oSheet.Name).Select
        oExcelFile.SaveAs sThisDestination, iCSV_Format
    Next

    '* Take Down
    oExcelFile.Close False
    oExcel.Quit

    ExportExcelFileToCSV = 0
    Exit Function
End Function

Function PromptForSkip(sFilename,oExcel)
    if not (VarType(gSkip) = vbEmpty) then
        PromptForSkip = gSkip
        Exit Function
    end if

    Dim oFSO
    Set oFSO = CreateObject("Scripting.FileSystemObject")

    sPrompt = vbCRLF & _
        "A filename was received that doesn't appear to be an Excel Document." & vbCRLF & _
        "Do you want to skip this and all other unrecognized files?  (Will only prompt this once)" & vbCRLF & _
        "" & vbCRLF & _
        "Yes    - Will skip all further files that don't have a .xl* extension" & vbCRLF & _
        "No     - Will pass the file to excel regardless of extension" & vbCRLF & _
        "Cancel - Abort any further conversions and exit this script" & vbCRLF & _
        "" & vbCRLF & _
        "The unrecognized file was:" & vbCRLF & _
        sFilename & vbCRLF & _
        "" & vbCRLF & _
        "The path returned by the system was:" & vbCRLF & _
        oFSO.GetAbsolutePathName(sFilename) & vbCRLF

    sTitle = "Unrecognized File Type Encountered"

    sResponse =  MsgBox (sPrompt,vbYesNoCancel,sTitle)
    Select Case sResponse
    Case vbYes
        gSkip = True
    Case vbNo
        gSkip = False
    Case vbCancel
        oExcel.Quit
        WScript.Quit(10)    '*  10 Is the error code I use to indicate there was a user abort (1 because wasn't successful, + 0 because the user chose to exit)
    End Select

    PromptForSkip = gSkip
    Exit Function
End Function
如果WScript.Arguments.Count<2,则
WScript.Echo“错误!请指定源路径和目标。用法:XlsToCsv SourcePath.xls destination.csv”
Wscript.Quit
如果结束
暗色oExcel
设置oExcel=CreateObject(“Excel.Application”)
Dim oBook
设置oBook=oExcel.Workbooks.Open(Wscript.Arguments.Item(0))
oBook.SaveAs WScript.Arguments.Item(1),6
好的,关上
oExcel,退出
Echo“完成”
然后从命令行转到保存.vbs文件的文件夹并运行:

XlsToCsv.vbs [sourcexlsFile].xls [destinationcsvfile].csv

不过,这需要在您所在的计算机上安装Excel。

Scott F的答案是我在互联网上找到的最好答案。我确实添加了他的代码来满足我的需要。我补充说:


错误恢复下一步我尝试了ScottF VB解决方案,并使其正常工作。但是,我想将多选项卡(工作簿)excel文件转换为单个.csv文件

这不起作用,只复制了一个选项卡(我通过excel打开它时突出显示的选项卡)


有人知道可以将多选项卡excel文件转换为单个.csv文件的脚本吗?

ScottF answer的稍微修改版本,不需要绝对文件路径:

if WScript.Arguments.Count < 2 Then
    WScript.Echo "Please specify the source and the destination files. Usage: ExcelToCsv <xls/xlsx source file> <csv destination file>"
    Wscript.Quit
End If

csv_format = 6

Set objFSO = CreateObject("Scripting.FileSystemObject")

src_file = objFSO.GetAbsolutePathName(Wscript.Arguments.Item(0))
dest_file = objFSO.GetAbsolutePathName(WScript.Arguments.Item(1))

Dim oExcel
Set oExcel = CreateObject("Excel.Application")

Dim oBook
Set oBook = oExcel.Workbooks.Open(src_file)

oBook.SaveAs dest_file, csv_format

oBook.Close False
oExcel.Quit
如果WScript.Arguments.Count<2,则
WScript.Echo“请指定源文件和目标文件。用法:ExcelToCsv”
Wscript.Quit
如果结束
csv_格式=6
设置objFSO=CreateObject(“Scripting.FileSystemObject”)
src_file=objFSO.GetAbsolutePathName(Wscript.Arguments.Item(0))
dest_file=objFSO.GetAbsolutePathName(WScript.Arguments.Item(1))
暗色oExcel
设置oExcel=CreateObject(“Excel.Application”)
Dim oBook
设置oBook=oExcel.Workbooks.Open(src_文件)
oBook.SaveAs dest_文件,csv_格式
好的,关上
oExcel,退出
我已经重命名了脚本ExcelToCsv,因为这个脚本根本不限于xls。正如我们所期望的那样,xlsx工作正常


使用Office 2010进行测试。

ScottF groovy VB脚本上的一个小扩展:此批处理文件将循环遍历目录中的.xlsx文件,并将其转储到*.csv文件中:

FOR /f "delims=" %%i IN ('DIR *.xlsx /b') DO ExcelToCSV.vbs "%%i" "%%i.csv"

注意:您可以将扩展名.xlsx更改为.xls,将脚本ExcelToCSV的名称更改为XlsToCsv

我需要从不同的工作表中提取几个CV,因此这里是一个修改版本的规划代码,允许您指定工作表名称

if WScript.Arguments.Count < 3 Then
    WScript.Echo "Please specify the sheet, the source, the destination files. Usage: ExcelToCsv <sheetName> <xls/xlsx source file> <csv destination file>"
    Wscript.Quit
End If

csv_format = 6

Set objFSO = CreateObject("Scripting.FileSystemObject")

src_file = objFSO.GetAbsolutePathName(Wscript.Arguments.Item(1))
dest_file = objFSO.GetAbsolutePathName(WScript.Arguments.Item(2))

Dim oExcel
Set oExcel = CreateObject("Excel.Application")

Dim oBook
Set oBook = oExcel.Workbooks.Open(src_file)

oBook.Sheets(WScript.Arguments.Item(0)).Select
oBook.SaveAs dest_file, csv_format

oBook.Close False
oExcel.Quit
如果WScript.Arguments.Count<3,则
Echo“请指定工作表、源文件和目标文件。用法:ExcelToCsv”
Wscript.Quit
如果结束
csv_格式=6
设置objFSO=CreateObject(“Scripting.FileSystemObject”)
src_file=objFSO.GetAbsolutePathName(Wscript.Arguments.Item(1))
dest_file=objFSO.GetAbsolutePathName(WScript.Arguments.Item(2))
暗色oExcel
设置oExcel=CreateObject(“Excel.Application”)
Dim oBook
设置oBook=oExcel.Workbooks.Open(src_文件)
oBook.Sheets(WScript.Arguments.Item(0))。选择
oBook.SaveAs dest_文件,csv_格式
好的,关上
oExcel,退出

基于Jon of All Trade提供的内容,以下(~n)消除了令人讨厌的双重扩展问题:
对于/f“delims=“%%i IN('DIR*.xlsx/b')DO exceltosv.vbs“%%i”“%%~ni.csv”

您可以使用用于数据库的Alacon命令行实用程序来执行此操作。它与Node.js一起工作,因此需要安装并打包

要将Excel文件转换为CVS(ot TSV),您可以输入:

> node alacon "SELECT * INTO CSV('mydata.csv', {headers:true}) FROM XLS('mydata.xls', {headers:true})"
默认情况下,Alasql从“Sheet1”转换数据,但您可以使用以下参数对其进行更改:

{headers:false, sheetid: 'Sheet2', range: 'A1:C100'}

Alacon支持其他类型的转换(CSV、TSV、TXT、XLSX、XLS)和SQL语言构造(请参见示例)。

此版本将处理从windows拖放的多个文件。 基于以上工作

Christian Lemer
plang
ScottF

打开记事本,创建一个名为XlsToCsv.vbs的文件,并将其粘贴到:

'* Usage: Drop .xl* files on me to export each sheet as CSV

'* Global Settings and Variables
Dim gSkip
Set args = Wscript.Arguments

For Each sFilename In args
    iErr = ExportExcelFileToCSV(sFilename)
    ' 0 for normal success
    ' 404 for file not found
    ' 10 for file skipped (or user abort if script returns 10)
Next

WScript.Quit(0)

Function ExportExcelFileToCSV(sFilename)
    '* Settings
    Dim oExcel, oFSO, oExcelFile
    Set oExcel = CreateObject("Excel.Application")
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    iCSV_Format = 6

    '* Set Up
    sExtension = oFSO.GetExtensionName(sFilename)
    if sExtension = "" then
        ExportExcelFileToCSV = 404
        Exit Function
    end if
    sTest = Mid(sExtension,1,2) '* first 2 letters of the extension, vb's missing a Like operator
    if not (sTest =  "xl") then
        if (PromptForSkip(sFilename,oExcel)) then
            ExportExcelFileToCSV = 10
            Exit Function
        end if
    End If
    sAbsoluteSource = oFSO.GetAbsolutePathName(sFilename)
    sAbsoluteDestination = Replace(sAbsoluteSource,sExtension,"{sheet}.csv")

    '* Do Work
    Set oExcelFile = oExcel.Workbooks.Open(sAbsoluteSource)
    For Each oSheet in oExcelFile.Sheets
        sThisDestination = Replace(sAbsoluteDestination,"{sheet}",oSheet.Name)
        oExcelFile.Sheets(oSheet.Name).Select
        oExcelFile.SaveAs sThisDestination, iCSV_Format
    Next

    '* Take Down
    oExcelFile.Close False
    oExcel.Quit

    ExportExcelFileToCSV = 0
    Exit Function
End Function

Function PromptForSkip(sFilename,oExcel)
    if not (VarType(gSkip) = vbEmpty) then
        PromptForSkip = gSkip
        Exit Function
    end if

    Dim oFSO
    Set oFSO = CreateObject("Scripting.FileSystemObject")

    sPrompt = vbCRLF & _
        "A filename was received that doesn't appear to be an Excel Document." & vbCRLF & _
        "Do you want to skip this and all other unrecognized files?  (Will only prompt this once)" & vbCRLF & _
        "" & vbCRLF & _
        "Yes    - Will skip all further files that don't have a .xl* extension" & vbCRLF & _
        "No     - Will pass the file to excel regardless of extension" & vbCRLF & _
        "Cancel - Abort any further conversions and exit this script" & vbCRLF & _
        "" & vbCRLF & _
        "The unrecognized file was:" & vbCRLF & _
        sFilename & vbCRLF & _
        "" & vbCRLF & _
        "The path returned by the system was:" & vbCRLF & _
        oFSO.GetAbsolutePathName(sFilename) & vbCRLF

    sTitle = "Unrecognized File Type Encountered"

    sResponse =  MsgBox (sPrompt,vbYesNoCancel,sTitle)
    Select Case sResponse
    Case vbYes
        gSkip = True
    Case vbNo
        gSkip = False
    Case vbCancel
        oExcel.Quit
        WScript.Quit(10)    '*  10 Is the error code I use to indicate there was a user abort (1 because wasn't successful, + 0 because the user chose to exit)
    End Select

    PromptForSkip = gSkip
    Exit Function
End Function

所有这些答案都帮助我构建了以下脚本,通过将一个或多个文件放到脚本上(或通过命令行),该脚本将自动将XLS*文件转换为CSV,反之亦然。抱歉,格式太僵硬了

' https://stackoverflow.com/questions/1858195/convert-xls-to-csv-on-command-line
' https://gist.github.com/tonyerskine/77250575b166bec997f33a679a0dfbe4

' https://stackoverflow.com/a/36804963/1037948
'* Global Settings and Variables
Set args = Wscript.Arguments

For Each sFilename In args
    iErr = ConvertExcelFormat(sFilename)
    ' 0 for normal success
    ' 404 for file not found
    ' 10 for file skipped (or user abort if script returns 10)
Next

WScript.Quit(0)

Function ConvertExcelFormat(srcFile)

    if IsEmpty(srcFile) OR srcFile = "" Then
        WScript.Echo "Error! Please specify at least one source path. Usage: " & WScript.ScriptName & " SourcePath.xls*|csv"
        ConvertExcelFormat = -1
        Exit Function
        'Wscript.Quit
    End If

    Set objFSO = CreateObject("Scripting.FileSystemObject")

    srcExt = objFSO.GetExtensionName(srcFile)

    ' the 6 is the constant for 'CSV' format, 51 is for 'xlsx'
    ' https://msdn.microsoft.com/en-us/vba/excel-vba/articles/xlfileformat-enumeration-excel
    ' https://www.rondebruin.nl/mac/mac020.htm
    Dim outputFormat, srcDest

    If LCase(Mid(srcExt, 1, 2)) = "xl" Then
        outputFormat = 6
        srcDest = "csv"
    Else
        outputFormat = 51
        srcDest = "xlsx"
    End If

    'srcFile = objFSO.GetAbsolutePathName(Wscript.Arguments.Item(0))
    srcFile = objFSO.GetAbsolutePathName(srcFile)
    destFile = Replace(srcFile, srcExt, srcDest)

    Dim oExcel
    Set oExcel = CreateObject("Excel.Application")
    Dim oBook
    Set oBook = oExcel.Workbooks.Open(srcFile)
    ' preserve formatting? https://stackoverflow.com/a/8658845/1037948
    'oBook.Application.Columns("A:J").NumberFormat = "@"
    oBook.SaveAs destFile, outputFormat
    oBook.Close False
    oExcel.Quit
    WScript.Echo "Conversion complete of '" & srcFile & "' to '" & objFSO.GetFileName(destFile) & "'"

End Function

:适用于UTF-8,适用于Microsoft Office 2016及更高版本

请尝试以下代码:

if WScript.Arguments.Count < 2 Then
    WScript.Echo "Please specify the source and the destination files. Usage: ExcelToCsv <xls/xlsx source file> <csv destination file>"
    Wscript.Quit
End If

csv_format = 62

Set objFSO = CreateObject("Scripting.FileSystemObject")

src_file = objFSO.GetAbsolutePathName(Wscript.Arguments.Item(0))
dest_file = objFSO.GetAbsolutePathName(WScript.Arguments.Item(1))


Dim oExcel
Set oExcel = CreateObject("Excel.Application")

Dim oBook
Set oBook = oExcel.Workbooks.Open(src_file)

oBook.SaveAs dest_file, csv_format

oBook.Close False
oExcel.Quit
如果WScript.Arguments.Count<2,则
WScript.Echo“请指定源文件和目标文件。用法:ExcelToCsv”
Wscript.Quit
如果结束
csv_格式=62
设置objFSO=CreateObject(“Scripting.FileSystemObject”)
src_file=objFSO.GetAbsolutePathName(Wscript.Arguments.Item(0))
dest_file=objFSO.GetAbsolutePathName(WScript.Arguments.Item(1))
暗色oExcel
设置oExcel=CreateObject(“Excel.Application”)
Dim oBook
设置oBook=oExcel.Workbooks.Open(src_文件)
oBook.SaveAs dest_文件,csv_格式
好的,关上
oExcel,退出

在桌面上创建一个名为“xls2csv.vbs”的TXT文件,并粘贴代码:

Dim vExcel
Dim vCSV
Set vExcel = CreateObject("Excel.Application")
Set vCSV = vExcel.Workbooks.Open(Wscript.Arguments.Item(0))
vCSV.SaveAs WScript.Arguments.Item(0) & ".csv", 6
vCSV.Close False
vExcel.Quit
将XLS文件拖到其中(如“test.XLS”)。它将创建一个名为“test.xls.CSV”的转换CSV文件。然后,将其重命名为