タブ区切りのテキスト ファイルを読み取り、いくつかの変更を加えてから、Excel 2007 .xlsx ファイルを作成する小さなアプリを作成しています。タブを使用して行を列に分割し、文字列配列から行を取得して Excel ファイルに書き込む方法がわかりません。それが理にかなっていることを願っています。
次のようなものが含まれてstring Lines[]
います:
Item1\tItem2\tItem3\tItem4
ItemA\tItemB\tItemC\tItemD
Item5\tItem6\tItem7\tItem8
次のようなExcelファイルを作成したいと思います。
A B C D
Item1 Item2 Item3 Item4
ItemA ItemB ItemC ItemD
Item5 Item6 Item7 Item8
私は次のことを試しましたが、最初の行を各行に入れるだけで、Lines[]
列に分けません:
string Lines[] = GetLines();
Excel.Application xlApp;
Excel.Workbook xlWb;
Excel.Worksheet xlWs;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWb = xlApp.Workbooks.Add(misValue);
xlWs = (Excel.Worksheet)xlWb.Worksheets.get_Item(1);
Excel.Range c1 = (Excel.Range)xlWs.Cells[2, 1];
Excel.Range c2 = (Excel.Range)xlWs.Cells[2 + lines.Length, 1];
Excel.Range range = xlWs.get_Range(c1, c2);
range.Value = lines;
range.TextToColumns(
range,
Microsoft.Office.Interop.Excel.XlTextParsingType.xlDelimited,
Microsoft.Office.Interop.Excel.XlTextQualifier.xlTextQualifierNone,
false,
true // This is flag to say it is tab delimited
);
xlApp.Visible = true;
アドバイスをいただければ幸いです。ありがとうございました!
これが私が現在得ている出力です:
A B C D
Item1\tItem2\tItem3\tItem4
Item1\tItem2\tItem3\tItem4
Item1\tItem2\tItem3\tItem4
編集: @jiverson の提案でコードを更新しました。行は Excel の列に分割されていますが、最初のLines[]
行は Excel のすべての行に表示されます。なんで?
編集 #2: 更新された作業コードは次のとおりです。
Excel.Application xlApp;
Excel.Workbook xlWb;
Excel.Worksheet xlWs;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWb = xlApp.Workbooks.Add(misValue);
xlWs = (Excel.Worksheet)xlWb.Worksheets.get_Item(1);
int currentRow = 2;
string[] lines = GetLines();
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i]; //get the current line
string[] values = line.Split('\t'); //split the line at the tabs
//
// .. i do some things to specific values here ..
//
lines[i] = String.Join("\t", values); //put the updated line back together
Excel.Range currentRange = (Excel.Range)xlWs.Cells[currentRow, 1]; //get the next row
currentRange.Value = lines[i]; //write the line to Excel
currentRow++;
}
Excel.Range c1 = (Excel.Range)xlWs.Cells[2, 1]; //get the first cell
Excel.Range c2 = (Excel.Range)xlWs.Cells[2 + lines.Length, 1]; //get the last cell
Excel.Range range = xlWs.get_Range(c1, c2); //set the range as the used area
range.TextToColumns( //split the row into columns
range,
Excel.XlTextParsingType.xlDelimited,
Excel.XlTextQualifier.xlTextQualifierNone,
false,
true // This is flag to say it is tab delimited
);