C#でエクセルファイルの読み込み
C#の勉強を兼ねてExcelファイル(.xls, .xlsx)を読み込み、文字列をCSVファイルとして出力するソフトを作成しました。
Excelファイルを読み込むためにExcelDataReaderを利用しています。
VisualStudioのパッケージマネージャでプロジェクトへ インストールできます。
引数で渡されたパスのエクセルファイルを読み込み文字列の配列として返す関数です。
ヘッダー等を読み飛ばせるように行、列をそれぞれ上、左からいくつ読み飛ばすかを変数”skip~~”で指定しています。
private static string[] ReadExcelData(string file_path)
{
List<string> lines = new List<string>();
var file = new FileInfo(file_path);
using (FileStream fs = file.Open(FileMode.Open))
{
IExcelDataReader reader;
if (file.Extension.Equals(".xls"))
{
reader = ExcelDataReader.ExcelReaderFactory.CreateBinaryReader(fs);
}
else
if (file.Extension.Equals(".xlsx"))
{
reader = ExcelDataReader.ExcelReaderFactory.CreateOpenXmlReader(fs);
}
else
{
throw new Exception("対応していない拡張子");
}
var conf = new ExcelDataSetConfiguration
{
ConfigureDataTable = _ => new ExcelDataTableConfiguration
{
UseHeaderRow = false
}
};
var dataSet = reader.AsDataSet(conf);
var dataTable = dataSet.Tables[0];
int rowsLen = dataTable.Rows.Count;
int colsLen = dataTable.Columns.Count;
for (int row = 0; row < rowsLen; row++)
{
if ((row < skipRows))
{
continue;
}
List<string> line = new List<string>();
StringBuilder sb = new StringBuilder();
sb.Clear();
for (int col = 0; col < colsLen; col++)
{
if ((col < skipCols))
{
continue;
}
var data = dataTable.Rows[row][col];
line.Add(data.ToString());
}
string lineStr = string.Join(",", line.ToArray());
lines.Add(lineStr);
}
string[] linesArray = lines.ToArray();
fs.Close();
return linesArray;
}
}
メイン関数です。
コマンドラインから引数でエクセルファイルを指定するか、
.exeファイルにエクセルファイルをドラッグアンドドロップすることで
指定したディレクトリに指定したファイル名で出力します。
出力ディレクトリやファイル名を変更するたびに
再コンパイルする必要が無いように、
それぞれ外部ファイルから設定を読み込みようにしています。
可変長引数の文字列から拡張子をチェックし
コマンドライン引数で指定された場合と、
ドラッグアンドドロップで指定された場合の両方に対応しています。
static void Main(string[] args)
{
string[] files = System.Environment.GetCommandLineArgs();
// 総合設定
GeneralSetting generalSetting = loadGeneralSetting();
skipRows = generalSetting.skip_rows;
skipCols = generalSetting.skip_cols;
if (files.Length > 0)
{
if (Directory.Exists(generalSetting.output_directry) == false)
{
Directory.CreateDirectory(generalSetting.output_directry);
}
int targetIndex = 0;
if (files[targetIndex].EndsWith(".exe"))
{
targetIndex++;
}
if (files[targetIndex] != null)
{
mFilePath = files[targetIndex];
string[] source = ReadExcelData(mFilePath);
int len = source.Length;
string outputPath = string.Concat(generalSetting.output_directry, generalSetting.output_file);
using (StreamWriter writer = new StreamWriter(outputPath, false, Encoding.UTF8))
{
for (int i = 0; i < len; i++)
{
writer.WriteLine(source[i]);
}
}
}
}
return;
}
ExcelDataReaderのおかげでかなり簡単に
エクセルファイルからセルの文字列を読み込むことができました。
ExcelにCSVファイルとして出力する機能があるので、
このままだとあまり利用することはなさそうですね。
水曜担当:Tanaka
tanaka at 2019年09月11日 10:00:49