programing

명령줄에서 XLS를 CSV로 변환

newnotes 2023. 4. 20. 22:40
반응형

명령줄에서 XLS를 CSV로 변환

Windows 명령줄에서 XLS 파일을 CSV 파일로 변환하려면 어떻게 해야 합니까?

머신에 Microsoft Office 2000이 인스톨 되어 있다.Microsoft Office를 사용할 수 없는 경우 Open Office를 설치할 수 있습니다.

메모장을 열고 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을 탑재하고 있는 머신에 설치해야 합니다.

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

이 스크립트는 xls에 한정되지 않기 때문에 ExcelToCsv라는 이름을 변경했습니다.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로 변경할 수 있습니다.

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

여기 사용법을 설명하는 게시물이 있습니다.

Windows PowerShell을 사용하여 Microsoft Excel을 자동화하는 방법

다른 워크시트에서 여러 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

다음은 여러 파일을 창에서 끌어다 놓는 작업을 처리하는 버전입니다.상기 작업에 의거하여

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

Alasql 데이터베이스의 Alacon 명령줄 유틸리티를 사용하여 실행할 수 있습니다.Node.js와 연동되므로 Node.js를 설치한 후 Alasql 패키지를 설치해야 합니다.

Excel 파일을 (TSV가 아닌) CVS로 변환하려면 다음과 같이 입력합니다.

> 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 언어 구성(예: 사용자 매뉴얼 참조)을 지원합니다.

직접 써보는 게 어때요?

당신의 프로필을 보니 적어도 C#/는 가지고 계신 것 같습니다.NET 익스피리언스Windows 콘솔 애플리케이션을 만들고 무료 Excel 리더를 사용하여 Excel 파일을 읽을 수 있습니다.CodePlex에서 사용할 수 있는 Excel Data Reader를 문제없이 사용하고 있습니다(한 가지 좋은 점은 Excel을 설치할 필요가 없다는 것입니다).명령줄에서 콘솔애플리케이션을 호출할 수 있습니다.

만약 당신이 이곳에 갇힌 것을 발견한다면, 나는 당신이 도움을 받을 것이라고 나는 확신한다.

: : : 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

Windows에 내장된 Excel OLEDB 데이터 공급자가 있습니다. 이를 사용하여 ADO를 통해 Excel 시트를 '쿼리'할 수 있습니다.결과를 CSV 파일에 씁니다.소량의 코딩이 필요하지만 기계에 아무것도 설치할 필요는 없습니다.

모든 거래의 존FOR /f "delims=" %%i IN ('DIR *.xlsx /b') DO ExcelToCSV.vbs "%%i" "%%~ni.csv"

데스크톱에 "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 파일이 생성됩니다.그런 다음 이름을 "test.csv"로 변경합니다.다 했어요.

ScottF VB 솔루션을 시험해 보고 작동했습니다.다만, 멀티탭(워크북) 엑셀 파일을 하나의 .csv 파일로 변환하고 싶었습니다.

이것은 동작하지 않고, 1개의 탭(엑셀로 열었을 때에 하이라이트 되는 탭)만 카피되었습니다.

멀티탭 엑셀 파일을 단일 .csv 파일로 변환할 수 있는 스크립트를 알고 있는 사람이 있습니까?

Scott F의 대답은 내가 인터넷에서 찾은 것 중 가장 좋다.난 내 욕구를 충족시키기 위해 그의 코드를 더했다.덧붙였습니다.

Error Resume Next <- 상단의 배치 처리에서 누락된 xls 파일을 설명합니다.oBook응용 프로그램.열("A:J")번호형식 = "@" <- SaveAs 행 앞에 데이터를 텍스트 형식으로 저장하여 Excel이 데이터의 선두 0을 삭제하고 숫자 문자열에서 쉼표를 삭제하지 않도록 합니다(예: 1,200 ~ 1200).컬럼 범위는 니드(A:J)에 맞게 조정해야 합니다.

또, 에코의 「완료」도 삭제해, 인터랙티브하지 않게 했습니다.

그런 다음 스크립트를 cmd 배치 파일에 추가하여 작업을 통해 1시간 단위로 자동 데이터를 처리했습니다.

이러한 답변은 모두 스크립트에 1개 이상의 파일을 드롭(또는 명령줄 경유)함으로써 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

콤마/탭 대신 csv 파일에 LOCAL 딜리미터를 표시하는 방법을 알고 싶다면 다음과 같이 하십시오.이것은 찾기가 매우 어려웠고 2022년까지 아무도 그것을 마주치지 않았다니 놀랍다.

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

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)

local = true
csv_format = 6
oBook.SaveAs dest_file, csv_format, 0, 0, 0, 0, 0, 0, 0, 0, 0, local

oBook.Close False
oExcel.Quit

gocsv는 Windows에서 실행되며 종속성이 없는 뛰어난 명령줄 앱입니다(Microsoft Office, Libre Office, Python 없음).단일 gocsv.exe 바이너리입니다.동작시키려면 , 다음의 순서에 따릅니다.

  1. zip 파일을 다운로드합니다(현대 컴퓨터의 경우 gocsv-windows-amd64.zip, 구형 컴퓨터의 경우 386).
  2. 파일을 압축 해제하고 gocsv.exe 바이너리를 Windows PATH 내 어딘가로 이동합니다(C:\WINDOWS는 보통 동작합니다).
  3. 다음과 같이 gocsv xlsx 명령을 실행합니다.
gocsv xlsx file.xlsx

언급URL : https://stackoverflow.com/questions/1858195/convert-xls-to-csv-on-command-line

반응형