在命令行上将XLS转换为CSV

时间:2009-12-07 06:24:22

标签: windows excel csv

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

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

15 个答案:

答案 0 :(得分:109)

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

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"

然后从命令行转到保存.vbs文件的文件夹并运行:

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

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

答案 1 :(得分:68)

ScottF答案的略微修改版本,不需要绝对文件路径:

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

我已经重命名了ExcelToCsv脚本,因为这个脚本根本不限于xls。 xlsx工作正常,正如我们所料。

使用Office 2010进行测试。

答案 2 :(得分:21)

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

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

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

答案 3 :(得分:16)

使用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()

这是一篇解释如何使用它的帖子

How Can I Use Windows PowerShell to Automate Microsoft Excel?

答案 4 :(得分:7)

我需要从不同的工作表中提取几个cvs,所以这里有一个plang代码的修改版本,允许你指定工作表名称。

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

答案 5 :(得分:7)

这是一个可以处理从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

答案 6 :(得分:5)

为什么不写自己的?

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

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

答案 7 :(得分:3)

您可以使用Alacon - Alasql数据库的命令行实用程序。它适用于Node.js,因此您需要安装Node.js然后安装Alasql包。

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

> node alacon "SELECT * INTO CSV('mydata.csv', {headers:true}) FROM XLS('mydata.xls', {headers:true})"

默认情况下,Alasql会转换来自&#34; Sheet1&#34;的数据,但您可以使用参数更改它:

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

Alacon支持其他类型的转换(CSV,TSV,TXT,XLSX,XLS)和SQL语言结构(例如,请参阅User Manual)。

答案 8 :(得分:2)

在所有交易的Jon提供的基础上,以下(~n)删除了讨厌的双扩展问题: FOR /f "delims=" %%i IN ('DIR *.xlsx /b') DO ExcelToCSV.vbs "%%i" "%%~ni.csv"

答案 9 :(得分:1)

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

答案 10 :(得分:1)

我尝试了ScottF VB解决方案并让它发挥作用。但是我想将多标签(工作簿)excel文件转换为单个.csv文件。

这不起作用,只有一个标签(通过excel打开时突出显示的标签)被复制。

是否有人知道可以将多标签Excel文件转换为单个.csv文件的脚本?

答案 11 :(得分:1)

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

$("#generate-payslip").click(function (e) {
    e.preventDefault();
    $.ajax({
        type: 'POST',
        url: 'generate-payslip.php',
        data: $('.form-pdf').serialize(),
        dataType: 'json',
        success: function (resp) {
            if (resp.response == "ok") {

                $('#payslip-title').html("SLIP GAJI " + returnbulan(resp.bulan) + " " + resp.tahun);
                $("#cabang").html(resp.cabang);
                $('#u_gaji_pokok').html(resp.u_gaji_pokok);
            }
        })

将XLS文件拖到其中(例如“ test.xls”)。它将创建一个名为“ test.xls.csv”的转换后的CSV文件。然后,将其重命名为“ test.csv”。完成。

答案 12 :(得分:0)

斯科特F的答案是我在互联网上找到的最好的答案。我确实添加了他的代码以满足我的需求。我补充说:

On Error Resume Next &lt; - 在顶部的批处理中说明缺少的xls文件。 oBook.Application.Columns(“A:J”)。NumberFormat =“@”&lt; - 在SaveAs行之前,确保我的数据保存为文本格式,以防止excel删除前导零和消除我的数据中的数字字符串中的逗号,即(1,200到1200)。应调整色谱柱范围以满足您的需要(A:J)。

我还删除了Echo“done”以使其不具有交互性。

然后我将脚本添加到cmd批处理文件中,以便通过任务每小时处理一次自动数据。

答案 13 :(得分:0)

所有这些答案都帮助我构建了以下脚本,该脚本通过将一个或多个文件拖放到脚本中(或通过命令行)来自动将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

答案 14 :(得分:0)

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

尝试以下代码:

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