将多个CSV文件另存为XLS

时间:2014-02-13 22:26:10

标签: excel powershell csv xls

我是PS的总菜鸟,我在尝试将CS​​V文件的文件夹保存到XLS或XLSX时遇到了麻烦。我可以为一个文件做到这一点,但无法解决我多次做错的事情。

CLS
$path = "H:\My Documents\"
$files = Get-ChildItem $path -include *.csv -recurse
echo $files
foreach($file in $files) {
$objExcel=New-Object -com "Excel.Application" 
$objWorkbook=$objExcel.workbooks.open($file)
$objWorksheet=$objWorkbook.Worksheets.Item(1)

#insert COUNTIF formula into cell A8
$strFormula = "=COUNTIF(I6:I1000," + [char](34) + ">0" + [char](34) + ")"
$objExcel.Cells.Item(1, 8).Formula = $strFormula

#Save as XLS
$xlout=$file.Replace('.csv','xlsx') 
$objWorkbook.SaveAs($xlOut,51) 

$objWorkbook.Close()
$objExcel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objExcel)
}

有人能帮助我吗?

1 个答案:

答案 0 :(得分:2)

好吧,我没有看到任何根本错误,但可能是Excel快速连续开启和关闭的问题。尝试将循环移动到打开和关闭Excel的时间范围内。

CLS
$path = "H:\My Documents\"
$files = Get-ChildItem $path -include *.csv -recurse
echo $files
$objExcel=New-Object -com "Excel.Application" 
foreach($file in $files) {
    $objWorkbook=$objExcel.workbooks.open($file)
    $objWorksheet=$objWorkbook.Worksheets.Item(1)

    #insert COUNTIF formula into cell A8
    $strFormula = "=COUNTIF(I6:I1000," + [char](34) + ">0" + [char](34) + ")"
    $objExcel.Cells.Item(1, 8).Formula = $strFormula

    #Save as XLS
    $xlout=$file.FullName.Replace('.csv','.xlsx') 
    $objWorkbook.SaveAs($xlOut,51) 

    $objWorkbook.Close()
}
$objExcel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objExcel)

编辑:
我更新了$ xlout以获取FullName元素,并修复了它的替换,因为它丢失了.并且基本上将“somefile.csv”更改为“somefilexlsx”。