Search

2019/02/09

ExcelDataReaderでxlsとxlsxとcsvを読み込み:powershellでも動くよ

C#でxlsとxlsxとcsvを読み込み。
using ExcelDataReader;しておく。
たぶんpowershellでも使えると思う。
出力はEPPLUS使う。




xlsは読み込みだけでいいと思う。
出力はxlsxで。
でも、元ファイルはxlsもあるのでExcelDataReaderを使う。
ExcelDataReaderのAsDataSet()は使わないのでreaderを回す。
GetInt32()はキャストしてエラーになるので、GetValue()をvarで受けて
tostring()でキャストする。

次の1行に移動して読む
Read() reads a row from the current sheet.

指定の列のセルを読む
GetValue() returns a value from the current row as an object, or null if there is no value.

次のシートに移動
NextResult() advances the cursor to the next sheet.

コラムの個数
FieldCount returns the number of columns in the current sheet.

行の個数
RowCount returns the number of rows in the current sheet. This includes terminal
empty rows which are otherwise excluded by AsDataSet().






ExcelDataReader
https://github.com/ExcelDataReader/ExcelDataReader

EPPLUS
https://github.com/JanKallman/EPPlus


ExcelDataReader.dllはここから。
https://www.nuget.org/packages/ExcelDataReader/
ExcelDataReaderのAsDataSet()使うならここからdll入手する。
でも、getValueでもいけるよ。
https://www.nuget.org/packages/ExcelDataReader.DataSet/


using (FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read))
   {

    using (IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream))
    {
     
     m_aryBaseDatMaxCol = reader.FieldCount;
     m_aryBaseDatMaxRow = reader.RowCount;
     
     if( reader.FieldCount < MAX_NUM_COL && reader.RowCount < MAX_NUM_ROW)
     {
      int i = 0;
//      do {
      while (reader.Read()) {
       for(int j = 0 ; j < reader.FieldCount; j++)
       {
        var val reader.GetValue(j)
        m_aryBaseDat[i,j] = val.Tostring();
       }
       i++;
      }
//      }  while (reader.NextResult());//advances the cursor to the next sheet.
     }
    }
syntax2html

powershellだとこんな感じ?
Set-ExecutionPolicy RemoteSigned -Scope Process
[Reflection.Assembly]::LoadFile("c:\tmp\ExcelDataReader.dll");

$path = "c:\tmp\test.xls";
$f = New-Object IO.FileStream($path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)

$reader =[ExcelDataReader.ExcelReaderFactory]::CreateReader($f);

$aryV = New-Object "object[,]" $reader.RowCount, $reader.FieldCount;
[int] $i=0;
while($reader.Read())
{
    for([int] $j=0;$j -lt $reader.FieldCount;$j++)
    {
    $aryV[$i,$j] = $reader.GetValue($j);
    }
    $i++;
}

0 件のコメント:

コメントを投稿