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

杀马特。学长 韩版系。学妹 提交于 2020-12-26 06:35:52

问题


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.


回答1:


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 )


来源:https://stackoverflow.com/questions/24159542/how-do-i-convert-a-csv-file-to-xlsb-using-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!