문제

I'm a total noob to PS and I'm having trouble trying to save a folder of CSV files to XLS or XLSX. I can do it for a single file, but can't work out what I'm doing wrong to do it multiple times.

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)
}

Can someone help me please?

도움이 되었습니까?

해결책

Well, I don't see anything fundamentally wrong, but it may be having issues with Excel opening and closing in rapid succession. Try moving your loop to within the time frame of opening and closing 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)

Edit:
I updated $xlout to pull the FullName element, and also fixed it's replacement since it was losing the . and basically changing "somefile.csv" into "somefilexlsx".

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top