我有一个宏,它获取应该是文件的单元格的值,然后使用 xlwings 和 VBS 脚本将其转换为 csv 文件。这个宏被分配给一个按钮。
下面是一个示例函数:
import subprocess
from xlwings import Workbook, Range
def extract_excel_sheet_to_csv(filename, sheet_name, working_dir, csv_filename):
wb = Workbook.caller()
new_filename = os.path.join(working_dir, filename)
cmd = ''.join(['cscript extract_excel_sheet_to_csv.vbs "',
new_filename, '" "', sheet_name, '" "',
working_dir, '" "', csv_filename, '"'])
cmd = cmd.encode("utf8")
subprocess.call(cmd)
filename = Range(sheet_arxikh, status_cell).value # Example data.xlsb
sheet_name = u"Αρχείο"
working_dir = os.path.dirname(wb.fullname)
csv_filename = "data.csv"
convert_file(filename, sheet_name, working_dir, csv_filename)
wb.fullname 给出如下内容:"c:\projects\buy_sell\data.xlsb"
,因此 working_dir 将是"c:\projects\buy_sell\"
。这会在使用以下 VBS 脚本的文件路径中产生问题。如果我使用r"c:\projects\buy_sell"
它工作正常。
这是我使用的 VBS 脚本:
Set objFSO = CreateObject("Scripting.FileSystemObject")
src_file = Wscript.Arguments.Item(0)
sheet_name = Wscript.Arguments.Item(1)
dir_name = Wscript.Arguments.Item(2)
file_name = Wscript.Arguments.Item(3)
WScript.Echo src_file
WScript.Echo sheet_name
WScript.Echo dir_name + "\" + file_name + ".csv"
REM WScript.Echo dir_name
REM WScript.Echo file_name
Dim objExcel
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = False
Dim objWorkbook
Set objWorkbook = objExcel.Workbooks.open(src_file)
objWorkbook.Sheets(sheet_name).Copy
objExcel.DisplayAlerts = False
objExcel.ActiveWorkbook.SaveAs dir_name + "\" + file_name + ".csv", 6
objWorkbook.Close False
objExcel.Quit