foreachループから各要素を書き込む代わりに、構文ではforeachループの最後の値をすべてのセルに書き込むだけです。私はこれが私が見落としてきたものだと確信していますが、各行に応じてforeachループの各要素を書き込むように構文を変更する必要がありますか?より良い私の意図した結果が何であるかを説明するためにコードは最後のデータを繰り返しExcelに書き出します
foreach (var calcs in dictionary)
{
var FileInfo = new FileInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "WriteDataToExcelThroughCode.xlsx"));
using (ExcelPackage package = new ExcelPackage(FileInfo))
{
ExcelWorksheet ws = package.Workbook.Worksheets["TTest2"];
//ExcelWorksheet ws = package.Workbook.Worksheets[0];
ws.Cells["A24:C36"].Clear();
int z = 0;
int x = 24;
while (z <= numofrows)
{
ws.Cells["A" + x + ":A" + x].Value = calcs.Key;
ws.Cells["B" + x + ":B" + x].Value = dictionary[calcs.Key][0];
ws.Cells["C" + x + ":C" + x].Value = dictionary[calcs.Key][1];
//ws.Cells["D" + x + "D" + x].Value = dictionary[calcs.Key][2];
x = x + 1;
z = z + 1;
}
package.Save();
}
}
EDIT
次のように、です。 仮定CALCSは
James 1 2
Jose 3 4
Bob 5 6
は、私は次の情報は、以下の細胞
A24 =ジェームズ・B24 = 1 C24 = 2
A25 =ホセB25 = 3 C25 = 4
に書き込むことがしたい、次の情報が含まれていますA26 =ボブB26 = 5 C26 = 6
編集2
私の変数numofrows
がセットアップされるので、
int start = Convert.ToInt32(txtstart.Text);
int end = Convert.ToInt32(txtEnd.Text) + 1;
int numofrows = end - start;
int[] abc = Enumerable.Range(start, end-start).ToArray();
foreach (int a in abc)
{
Dictionary<int, int[]> dictionary = new Dictionary<int, int[]>();
dictionary.Add(a, new int[] { 2, 3 });
foreach (var calcs in dictionary)
{
// original code
}
}
private void btnHitIT_Click(object sender, EventArgs e)
{
int start = Convert.ToInt32(Alpha);
int end = Convert.ToInt32(AlphaEnd)+1;
int numofrows = end - start;
int[] angles = Enumerable.Range(start, end - start).ToArray();
foreach (int a in angles)
{
Dictionary<int, int[]> dictionary = new Dictionary<int, int[]>();
dictionary.Add("Jack", new int[] { 2, 3 });
dictionary.Add("James", new int[] { 7, 11 });
dictionary.Add("Jason", new int[] { 14, 21 });
pDrawingArea.Invalidate();
var FileInfo = new FileInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "WriteDataToExcelThroughCode.xlsx"));
using (ExcelPackage package = new ExcelPackage(FileInfo))
{
ExcelWorksheet ws = package.Workbook.Worksheets["TTest2"];
int x = 24;
foreach (var calcs in dictionary)
{
ws.Cells["A24:C36"].Clear();
for (int z = 0; z <= numofrows; ++z)
{
ws.Cells["A" + x + ":A" + x].Value = calcs.Key;
ws.Cells["B" + x + ":B" + x].Value = dictionary[calcs.Key][0];
ws.Cells["C" + x + ":C" + x].Value = dictionary[calcs.Key][1];
++x;
}
}
package.Save();
}
}
にその値が++ xとしていることを考えると
Dictionary
の値のために二回検索していることに気づきます。 ++ z;私と同じz = z + 1を設定する? –@YohanGreenburgはい。それを書く方法はいくつかあります( '++ x'、' x + = 1'、 'x = x + 1')。 '++ x'は' 1 'でインクリメントする最も明白な方法です – Vikhram
あなたの投稿の構文を利用して、最後の値のセットだけがExcelに書き込まれます –