Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

csv

excel

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.

like image 856
IordanouGiannis Avatar asked Jun 11 '14 09:06

IordanouGiannis


People also ask

How do I convert an Excel file to XLSB?

Save a file as xlsb by using Save As. Click on the Save as type to active the drop down menu. Select Excel Binary Workbook. Press the Save button.

Does Openpyxl work with CSV?

Converting a CSV file to ExcelYour code uses Python's csv module in addition to OpenPyXL. You create a function, csv_to_excel() , then accepts two arguments: csv_file - The path to the input CSV file.


1 Answers

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 )
like image 55
NorthCat Avatar answered Sep 21 '22 02:09

NorthCat