Câu trả lời:
Mở Notepad, tạo một tệp có tên XlsToCsv.vbs và dán tệp này vào:
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"
Sau đó, từ một dòng lệnh, hãy chuyển đến thư mục bạn đã lưu tệp .vbs và chạy:
XlsToCsv.vbs [sourcexlsFile].xls [destinationcsvfile].csv
Điều này yêu cầu Excel phải được cài đặt trên máy bạn đang sử dụng.
oExcel.Workbooks.Open
phù hợp với các chỉ số mong muốn của bảng tính (bắt đầu từ 1): oBook.Worksheets(1).Activate
Một phiên bản được sửa đổi một chút của câu trả lời ScottF, không yêu cầu đường dẫn tệp tuyệt đối:
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
Tôi đã đổi tên tập lệnh là ExcelToCsv, vì tập lệnh này không giới hạn ở xls. xlsx Hoạt động tốt, như chúng tôi có thể mong đợi.
Đã thử nghiệm với Office 2010.
Một phần mở rộng nhỏ trên tập lệnh VB thú vị của ScottF: tệp hàng loạt này sẽ lặp qua các tệp .xlsx trong một thư mục và kết xuất chúng vào tệp * .csv:
FOR /f "delims=" %%i IN ('DIR *.xlsx /b') DO ExcelToCSV.vbs "%%i" "%%i.csv"
Lưu ý: Bạn có thể thay đổi phần mở rộng .xlsx thành .xls và tên của tập lệnh ExcelToCSV thành XlsToCsv
Còn với PowerShell thì sao?
Mã phải trông như thế này, mặc dù không được kiểm tra
$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()
Đây là một bài giải thích cách sử dụng nó
Làm cách nào để sử dụng Windows PowerShell để tự động hóa Microsoft Excel?
$Excel.Workbooks.Open
phương pháp. Nó không thể tìm thấy tệp được chỉ định. Tôi đã giải quyết vấn đề này bằng cách sử dụng Get-Item
trên tệp và nối nó vào một ForEach-Object
vòng lặp (điều gì đó tôi sẽ kết thúc trong quá trình triển khai cuối cùng của mình) cho hai dòng bắt đầu $Workbook
.
CD /D C:\ && DIR YOURDOC.csv /s
. Hóa ra tệp đã được lưu vào Tài liệu của tôi theo mặc định. Vì vậy, bạn cần đưa nhiều hơn vào tập lệnh nếu bạn muốn lưu tệp vào cùng thư mục mà bạn đang làm việc (nếu không phải Tài liệu của tôi).
Tôi có nhu cầu trích xuất một số cv từ các trang tính khác nhau, vì vậy đây là phiên bản sửa đổi của mã plang cho phép bạn chỉ định tên trang tính.
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
Đây là một phiên bản sẽ xử lý nhiều tệp được kéo và thả từ các cửa sổ. Dựa trên các công trình trên của
Christian Lemer
plang
ScottF
Mở Notepad, tạo một tệp có tên XlsToCsv.vbs và dán tệp này vào:
'* 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
Tại sao bạn không tự viết?
Tôi thấy từ hồ sơ của bạn, bạn có ít nhất một số kinh nghiệm C # /. NET. Tôi muốn tạo một ứng dụng bảng điều khiển Windows và sử dụng trình đọc Excel miễn phí để đọc trong (các) tệp Excel của bạn. Tôi đã sử dụng Trình đọc dữ liệu Excel có sẵn từ CodePlex mà không gặp bất kỳ sự cố nào (một điều tuyệt vời: trình đọc này không yêu cầu cài đặt Excel). Bạn có thể gọi ứng dụng bảng điều khiển của mình từ dòng lệnh.
Nếu bạn thấy mình mắc kẹt, hãy đăng ở đây và tôi chắc chắn bạn sẽ nhận được sự trợ giúp.
Bạn có thể làm điều đó với Alacon - tiện ích dòng lệnh cho cơ sở dữ liệu Alasql . Nó hoạt động với Node.js, vì vậy bạn cần cài đặt Node.js và sau đó là gói Alasql .
Để chuyển đổi tệp Excel sang CVS (ot TSV), bạn có thể nhập:
> node alacon "SELECT * INTO CSV('mydata.csv', {headers:true}) FROM XLS('mydata.xls', {headers:true})"
Theo mặc định, Alasql chuyển đổi dữ liệu từ "Sheet1", nhưng bạn có thể thay đổi nó bằng các tham số:
{headers:false, sheetid: 'Sheet2', range: 'A1:C100'}
Alacon hỗ trợ các loại chuyển đổi khác (CSV, TSV, TXT, XLSX, XLS) và cấu trúc ngôn ngữ SQL (xem Hướng dẫn sử dụng để biết ví dụ).
Có một nhà cung cấp dữ liệu Excel OLEDB được tích hợp trong Windows; bạn có thể sử dụng điều này để 'truy vấn' trang tính Excel qua ADO.NET và ghi kết quả vào tệp CSV. Yêu cầu một lượng nhỏ mã hóa, nhưng bạn không cần phải cài đặt bất kỳ thứ gì trên máy.
Dựa trên những gì Jon of All Trades đã cung cấp, phần sau (~ n) đã loại bỏ vấn đề tiện ích mở rộng kép khó chịu:
FOR /f "delims=" %%i IN ('DIR *.xlsx /b') DO ExcelToCSV.vbs "%%i" "%%~ni.csv"
Tôi đã thử giải pháp ScottF VB và nó hoạt động. Tuy nhiên, tôi muốn chuyển đổi tệp excel nhiều tab (sổ làm việc) thành một tệp .csv duy nhất.
Điều này không hoạt động, chỉ có một tab (tab được đánh dấu khi tôi mở nó qua excel) được sao chép.
Có ai biết về tập lệnh có thể chuyển đổi tệp excel nhiều tab thành một tệp .csv duy nhất không?
Câu trả lời của Scott F là câu trả lời hay nhất mà tôi tìm thấy trên internet. Tôi đã thêm vào mã của anh ấy để đáp ứng nhu cầu của tôi. Tôi đã thêm:
Trên Lỗi Tiếp tục Tiếp tục <- Để giải thích cho việc thiếu các tệp xls trong quá trình xử lý hàng loạt của tôi ở trên cùng. oBook.Application.Columns ("A: J"). NumberFormat = "@" <- Trước dòng SaveAs để đảm bảo dữ liệu của tôi được lưu được định dạng dưới dạng văn bản để ngăn excel xóa số 0 đứng đầu và loại bỏ dấu phẩy trong chuỗi số trong dữ liệu của tôi tức là (1.200 đến 1200). Phạm vi cột phải được điều chỉnh để đáp ứng nhu cầu của bạn (A: J).
Tôi cũng đã loại bỏ Echo "xong" để làm cho nó không tương tác.
Sau đó, tôi đã thêm tập lệnh vào tệp hàng loạt cmd để xử lý dữ liệu tự động hàng giờ thông qua một tác vụ.
Tất cả các câu trả lời này đã giúp tôi xây dựng tập lệnh sau sẽ tự động chuyển đổi tệp XLS * sang CSV và ngược lại , bằng cách thả một hoặc nhiều tệp trên tập lệnh (hoặc qua dòng lệnh). Xin lỗi vì định dạng buồn tẻ.
' /programming/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
:: Đối với UTF-8 hoạt động cho Microsoft Office 2016 trở lên!
Hãy thử mã này:
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
Tạo tệp TXT trên màn hình của bạn có tên "xls2csv.vbs" và dán mã:
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
Kéo tệp XLS vào đó (như "test.xls"). Nó sẽ tạo một tệp CSV được chuyển đổi có tên "test.xls.csv". Sau đó, đổi tên nó thành "test.csv". Làm xong.