最近遇到了一個新事物,就是二維數組,它在我的C# 世界中幾乎沒有怎麼出現過,而我現在參與的項目中已經用到了。
首先二維數組是如何創建的呢?
//創建1,1開始的二維數組 bject[,] tFormula = (object[,])Array.CreateInstance(typeof(object), new int[] { 3, 4 }, new int[] { 1, 1 });
二維數組都是從1下標開始,這一點需要注意。我們知道Excel是一個個格子拼裝起來的,和二維數組非常類似。所以我們將excel數據拼裝進二維數組試一試,代碼如下。
for (int j = 0; j < dataGridTop.Rows.Count; j++) //循環行 { tFormula[j + 1, 1] = dataGridTop.Rows[j].Cells[1].Value; tFormula[j + 1, 2] = dataGridTop.Rows[j].Cells[2].Value; tFormula[j + 1, 3] = dataGridTop.Rows[j].Cells[3].Value; tFormula[j + 1, 4] = dataGridTop.Rows[j].Cells[4].Value; }
非常有趣,當然還可以將二維數組裝進Excel中。
worksheetInfoTarget.Range["C14:F28"].Value = tFormula;
注意,Range批量賦值中,一定要加EnableEvents處理,先關再開,否則會出現Vsto 事件無法觸發情況。