不使用Excel将xlsx转换为CSV

时间:2016-03-11 13:10:27

标签: powershell vbscript powershell-v2.0 export-to-csv powershell-v4.0

我收到以下错误:

Cannot index into a null array. 
At C:\tmp\Folder\excel\output\net45\test.ps1:14 char:1
+ $Data = $Reader.AsDataSet().Tables[0].Rows
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     + CategoryInfo : InvalidOperation: (:) [], RuntimeException
     + FullyQualifiedErrorId : NullArray
# Zero based index. The second row has index 1.
$StartRow = 2
# Input File
$InputFileName = "C:\tmp\Folder\excel\output\net20\test.xlsx"
# Output File
$OutputFileName = "C:\tmp\Folder\excel\output\net20\SomeFile.csv"
# Path to Excel.dll is saved (downloaded from http://exceldatareader.codeplex.com/)
$DllPath = "C:\tmp\Folder\excel\output\net45\Excel.4.5.dll"  

[void]([Reflection.Assembly]::LoadFrom($DllPath))

$Stream = New-Object IO.FileStream($InputFileName, "Open", "Read")
$Reader = [Excel.ExcelReaderFactory]::CreateBinaryReader($Stream)
$Data = $Reader.AsDataSet().Tables[0].Rows

# Read the column names. Order should be preserved
$Columns = $Data[$StartRow].ItemArray

# Sort the remaining data into an object using the specified columns
$Data[$($StartRow + 1)..$($Data.Count - 1)] | % {
  # Create an object
  $Output = New-Object Object
  # Read each column
  for ($i = 0; $i -lt $Columns.Count; $i++) {
    $Output | Add-Member NoteProperty $Columns[$i] $_.ItemArray[$i]
  }
  # Leave it in the output pipeline
  $Output
} | Export-CSV $OutputFileName -NoType

2 个答案:

答案 0 :(得分:2)

您正在调用二进制方法(.xls)并使用Open XML格式文件(.xlsx)。请尝试使用[Excel.ExcelReaderFactory]::CreateOpenXmlReader($Stream)

这对我有用:

$DllPath = 'C:\Excel.DataReader.45\Excel.4.5.dll';
$FilePath = 'C:\Students.xlsx';

$FileMode = [System.IO.FileMode]::Open;
$FileAccess = [System.IO.FileAccess]::Read;

Add-Type -Path $DllPath;

$FileStream = New-Object -TypeName System.IO.FileStream $FilePath, $FileMode, $FileAccess;

$ExcelDataReader = [Excel.ExcelReaderFactory]::CreateOpenXmlReader($FileStream);

$ExcelDataReader.IsFirstRowAsColumnNames = $true;

$ExcelDataSet = $ExcelDataReader.AsDataSet();

$ExcelDataReader.Dispose();
$FileStream.Close();
$FileStream.Dispose();

$ExcelDataSet.Tables | Format-Table -AutoSize

如果您仍然遇到问题,可以考虑使用与Office分开安装的Microsoft.ACE.OLEDB.12.0提供程序。有一些文档here

答案 1 :(得分:-2)

在我遇到类似疑问之前,我已经阅读了此"Convert XLS to CSV on command line"和此"convert-xlsx-file-to-csv-using-batch"。试试看它是否有帮助。