IordanouGiannis
IordanouGiannis

Reputation: 4357

How do I convert a csv file to xlsb using Python?

I want to convert a csv file to xlsb. I use the second answer from this Convert XLS to CSV on command line, which is the code below:

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

My code is the following:

import subprocess

subprocess.call("cscript CsvToExcel.vbs data.csv data.xlsb",
                stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) # Supress any messages

The problem is that I can't find the right value to put as the xlsb format. I have found this XlFileFormat Enumeration (Excel) which has the available values, but I am not sure which one is the one I need.

Useful Tip: If anyone tries to convert a csv with the first item in the first line is ID, an error will occur. Change the ID to id and it will be fine, more info SYLK: File format is not valid.

Upvotes: 7

Views: 7226

Answers (1)

NorthCat
NorthCat

Reputation: 9937

According this, xlsb format - is xlExcel12 with value 50 (51 In Excel for the Mac). Also, you can use pywin32 library for converting:

import win32com.client
excel = win32com.client.Dispatch("Excel.Application")
doc = excel.Workbooks.Open('D:\\input.csv')
doc.SaveAs( 'D:\\output_bin.xlsb', 50 )

Upvotes: 7

Related Questions