ある分析装置がxlsx形式でレポート出力するのでExcelのCOMインターフェース経由でCSVに落としてから処理していました。
この方法だとMicrosoft Excelが必須になってしまいます。
あとExcel本体経由なので、セキュリティ設定によっては手動でロック解除しないと開けないとかいう場合もあります。
そこでライセンス料をケチるべく、Excelなしでxls/xlsx -> CSV変換プログラムを書く方法を調べました。
// filename: Excel2CSV.cs
using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
namespace Excel2CSV
{
public class Excel2CSV
{
const int SUCCESS = 0;
const int MISSING_FILE_ERROR = 1;
const int FILE_EXTENSION_ERROR = 2;
public static int Main(string[] args)
{
string path = args[0];
var finfo = new FileInfo(path);
if (!finfo.Exists)
{
return MISSING_FILE_ERROR;
}
string connectionString;
switch (finfo.Extension.ToLower())
{
case ".xls":
connectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1;TypeGuessRows=0;\"", path);
break;
case ".xlsx":
connectionString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=NO;IMEX=1;\"", path);
break;
default:
return FILE_EXTENSION_ERROR;
}
OleDbConnection oleConn = new OleDbConnection(connectionString);
OleDbCommand oleCmd = new OleDbCommand();
OleDbDataReader oleReader;
oleConn.Open();
oleCmd.Connection = oleConn;
DataTable tables = oleConn.GetSchema("Tables");
foreach (DataRow row in tables.Rows)
{
string sheetName = row["TABLE_NAME"].ToString();
string sheetText = "";
try
{
sheetText += String.Format("[{0}]", sheetName) + Environment.NewLine;
oleCmd.CommandText = "SELECT * FROM [" + sheetName + "]";
oleReader = oleCmd.ExecuteReader();
while (oleReader.Read())
{
int fieldCount = oleReader.FieldCount;
string[] line = new string[fieldCount];
for (int i = 0; i < fieldCount; i++)
{
string val = oleReader[i].ToString();
double dval;
if (double.TryParse(val, out dval))
{
line[i] = dval.ToString(); // 12,345.67みたいな数字を12345.67に変換。
}
else
{
line[i] = val;
}
}
sheetText += String.Join(",", line) + Environment.NewLine;
}
oleReader.Close();
Console.WriteLine(sheetText);
}
catch
{
}
}
oleConn.Close();
oleCmd.Dispose();
oleConn.Dispose();
return SUCCESS;
}
}
} |
// filename: Excel2CSV.cs
using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
namespace Excel2CSV
{
public class Excel2CSV
{
const int SUCCESS = 0;
const int MISSING_FILE_ERROR = 1;
const int FILE_EXTENSION_ERROR = 2;
public static int Main(string[] args)
{
string path = args[0];
var finfo = new FileInfo(path);
if (!finfo.Exists)
{
return MISSING_FILE_ERROR;
}
string connectionString;
switch (finfo.Extension.ToLower())
{
case ".xls":
connectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1;TypeGuessRows=0;\"", path);
break;
case ".xlsx":
connectionString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=NO;IMEX=1;\"", path);
break;
default:
return FILE_EXTENSION_ERROR;
}
OleDbConnection oleConn = new OleDbConnection(connectionString);
OleDbCommand oleCmd = new OleDbCommand();
OleDbDataReader oleReader;
oleConn.Open();
oleCmd.Connection = oleConn;
DataTable tables = oleConn.GetSchema("Tables");
foreach (DataRow row in tables.Rows)
{
string sheetName = row["TABLE_NAME"].ToString();
string sheetText = "";
try
{
sheetText += String.Format("[{0}]", sheetName) + Environment.NewLine;
oleCmd.CommandText = "SELECT * FROM [" + sheetName + "]";
oleReader = oleCmd.ExecuteReader();
while (oleReader.Read())
{
int fieldCount = oleReader.FieldCount;
string[] line = new string[fieldCount];
for (int i = 0; i < fieldCount; i++)
{
string val = oleReader[i].ToString();
double dval;
if (double.TryParse(val, out dval))
{
line[i] = dval.ToString(); // 12,345.67みたいな数字を12345.67に変換。
}
else
{
line[i] = val;
}
}
sheetText += String.Join(",", line) + Environment.NewLine;
}
oleReader.Close();
Console.WriteLine(sheetText);
}
catch
{
}
}
oleConn.Close();
oleCmd.Dispose();
oleConn.Dispose();
return SUCCESS;
}
}
}
コンパイルは、
ファイル名を引数に与えると、標準出力にCSVを出力します。エラーは終了コードで通知します。
Excel2CSV.exe sample.xlsx > sample.xlsx.csv
echo %ERRORLEVEL%
0 |
Excel2CSV.exe sample.xlsx > sample.xlsx.csv
echo %ERRORLEVEL%
0
必須コンポーネント
Microsoft Access Database Engine 2010 Redistributable
.NET Framework 2.0 以上?
.NET Framework 4.0向けに コンパイルしたもの Excel2CSV
ただ、COM経由で取得したCSVとは、数値の値が違うことがあります。
原因はDAOを使った場合は、表示書式を適用した後の値しか取得できないためのようです。
たとえば、12345.6789という数値を持つセルに、"小数以下桁数2桁、桁区切り"という書式が設定されている場合、12,345.68が抽出されます。
考え方によってはこの方がいいというケースも、だめなケースもあるかも知れません。
とりあえず、桁区切り(,)の書式はCSVにとって邪魔なので、上記のプログラムでは数値とみなせる文字列は一旦数値に変換しています。
ちなみにxdoc2txtの場合は、桁区切りなし、四捨五入済みの数値を吐きます。
というか、いろいろ実験してたらxdoc2txtの出力ってゴミが入ってたりしてプログラムから後処理するのがめんどくさげ。
そもそも商用ライセンスは1000本単位じゃないと買えないので却下。
あと、xlsxをxlsに変換してExcel2CSVにかけると、可視シートだけが出力されるという微妙な違いもありました。
普通は隠しシートの内容を見たいということはないと思いますが。