명령 줄에서 XLS를 CSV로 변환
Windows 명령 줄에서 XLS 파일을 CSV 파일로 어떻게 변환 할 수 있습니까?
컴퓨터에 Microsoft Office 2000이 설치되어 있습니다. Microsoft Office를 사용할 수없는 경우 OpenOffice를 사용할 수 있습니다.
메모장을 쓰고 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의 멋진 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을 사용해야합니까?
다른 워크 시트에서 여러 개의 워크 시트 이름을 추출해야하는 여러 개의 워크 시트 이름을 코드가 있습니다.
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
직접 작성해 보지 보장겠습니까?
귀하의 프로필에서 최소한 C # /. NET 경험이있는 것으로 보입니다. Windows 콘솔 응용 프로그램을 만들고 무료 Excel 리더를 사용하여 Excel 파일을 읽습니다. CodePlex에서 제공 하는 Excel Data Reader 를 아무 문제없이 사용했습니다 (한 가지 좋은 점 :이 리더는 Excel을 설치할 필요가 없습니다). 명령 줄에서 콘솔 애플리케이션을 호출 할 수 있습니다.
여기에 갇힌 게시물을 발견하면 도움을받을 수있을 것입니다.
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은 "Sheet1"의 데이터를 변환하지만 매개 변수를 사용하여 변경할 수 있습니다.
{headers:false, sheetid: 'Sheet2', range: 'A1:C100'}
Alacon은 다른 유형의 변환 (CSV, TSV, TXT, XLSX, XLS) 및 SQL 언어 구성을 지원합니다 ( 예는 사용 설명서 참조 ).
Jon of All Trades가 제공 한 것을 기반으로 다음 (~ n)은 성가신 이중 확장 문제를 제거했습니다. FOR /f "delims=" %%i IN ('DIR *.xlsx /b') DO ExcelToCSV.vbs "%%i" "%%~ni.csv"
Windows에 내장 된 Excel OLEDB 데이터 공급자가 있습니다. 이를 사용하여 ADO.NET을 통해 Excel 시트를 '쿼리'하고 결과를 CSV 파일에 쓸 수 있습니다. 약간의 코딩이 필요하지만 머신에 아무것도 설치할 필요가 없습니다.
ScottF VB 솔루션을 사용해 보았고 작동했습니다. 그러나 다중 탭 (통합 문서) 엑셀 파일을 단일 .csv 파일로 변환하고 싶었습니다.
이것은 작동하지 않았고 하나의 탭 (엑셀을 통해 열 때 강조 표시된 탭) 만 복사되었습니다.
멀티탭 엑셀 파일을 단일 .csv 파일로 변환 할 수있는 스크립트를 알고있는 사람이 있습니까?
Scott F의 대답은 내가 인터넷에서 찾은 최고입니다. 나는 내 요구를 충족시키기 위해 그의 코드를 추가했습니다. 나는 추가했다 :
On Error Resume Next <-맨 위에있는 일괄 처리에서 누락 된 xls 파일을 설명합니다. oBook.Application.Columns ( "A : J"). NumberFormat = "@" <-내 데이터의 선행 0을 삭제하고 내 데이터의 숫자 문자열에서 쉼표를 제거하는 것을 방지하기 위해 내 데이터가 텍스트 형식으로 저장되도록 SaveAs 줄 앞에 즉 (1,200 ~ 1200). 필요에 맞게 컬럼 범위를 조정해야합니다 (A : J).
또한 Echo "done"을 제거하여 비대화 형으로 만들었습니다.
그런 다음 작업을 통해 시간 단위로 자동화 된 데이터를 처리하기 위해 스크립트를 cmd 배치 파일에 추가했습니다.
이 모든 답변 은 스크립트에 (또는 명령 줄을 통해) 하나 이상의 파일을 드롭 하여 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
참고 URL : https://stackoverflow.com/questions/1858195/convert-xls-to-csv-on-command-line
'IT' 카테고리의 다른 글
git이 "자동 모드"에서 작동 할 수 있습니까? (0) | 2020.08.27 |
---|---|
UnicodeDecodeError : 'ascii'코덱은 위치 2에서 0xd1 바이트를 사용할 수 없습니다. 서 수가 범위에 없습니다 (128). (0) | 2020.08.27 |
같은 줄에 에코를 표시하고 업데이트하는 방법 (0) | 2020.08.27 |
Python에서 순환 가져 오기 오기를 피하는 방법은 무엇입니까? (0) | 2020.08.27 |
첫 번째 마이너스와 마지막 마이너스의 CSS 선택기 (0) | 2020.08.27 |