C#如何改善循环填充Excel单元格

我主要是从一个文本文件parsing大量的文本,然后将其填充到一个Excel中。

//populate into worksheet for (int x = 0; x < rawLine.Length; x++) { string[] tempLine = rawLine[x].Split(';'); for (int y = 0; y < tempLine.Length; y++) { DateTime hour = Convert.ToDateTime(tempLine[6]); xlWorkSheet.Cells[y + 2, 1] = tempLine[0]; xlWorkSheet.Cells[y + 2, 2] = tempLine[1]; xlWorkSheet.Cells[y + 2, 3] = tempLine[2]; xlWorkSheet.Cells[y + 2, 4] = tempLine[3]; xlWorkSheet.Cells[y + 2, 5] = tempLine[4]; xlWorkSheet.Cells[y + 2, 6] = tempLine[5]; xlWorkSheet.Cells[y + 2, 7] = tempLine[6]; xlWorkSheet.Cells[y + 2, 8] = tempLine[7]; xlWorkSheet.Cells[y + 2, 9] = tempLine[8]; xlWorkSheet.Cells[y + 2, 10] = tempLine[9]; xlWorkSheet.Cells[y + 2, 11] = tempLine[10]; xlWorkSheet.Cells[y + 2, 12] = hour.Hour; xlWorkSheet.Cells[y + 2, 13] = tempLine[8] == "0" ? "SAME" : tempLine[9]; } Console.WriteLine("Current line = " + x + "\n"); } 

目前这个代码工作,但它只是太长了。 有反正加快吗? 我做了一些search,但没有发现什么具体的东西。

提前致谢。

这可能是一个非常小的改进,但是这一行:

 DateTime hour = Convert.ToDateTime(tempLine[6]); 

应该移到y循环之外,因为它不依赖于它。

除此之外,您可能应该考虑以某种方式同时设置多个单元格 – 大部分时间可能会花费在往返于Excel的时间。 (看起来这是@Gusman在评论中所build议的)。

Mohit的回答也很好,因为它更短,更简单。

你可以试试:

 //populate into worksheet DateTime hour; string[] tempLine; StringBuilder output = new StringBuilder(); for (int x = 0; x < rawLine.Length; x++) { tempLine = rawLine[x].Split(';'); for (int y = 0; y < tempLine.Length; y++) { hour = Convert.ToDateTime(tempLine[6]); xlWorkSheet.Cells[y + 2, 1] = tempLine[0]; xlWorkSheet.Cells[y + 2, 2] = tempLine[1]; xlWorkSheet.Cells[y + 2, 3] = tempLine[2]; xlWorkSheet.Cells[y + 2, 4] = tempLine[3]; xlWorkSheet.Cells[y + 2, 5] = tempLine[4]; xlWorkSheet.Cells[y + 2, 6] = tempLine[5]; xlWorkSheet.Cells[y + 2, 7] = tempLine[6]; xlWorkSheet.Cells[y + 2, 8] = tempLine[7]; xlWorkSheet.Cells[y + 2, 9] = tempLine[8]; xlWorkSheet.Cells[y + 2, 10] = tempLine[9]; xlWorkSheet.Cells[y + 2, 11] = tempLine[10]; xlWorkSheet.Cells[y + 2, 12] = hour.Hour; xlWorkSheet.Cells[y + 2, 13] = tempLine[8] == "0" ? "SAME" : tempLine[9]; } output.AppendLine("Current line = " + x); } Console.WriteLine(output.ToString()); 

可能只是为了改善循环,你可以这样写。 这不会改善性能,但看起来更干净。

 for (int x = 0; x < rawLine.Length; x++) { string[] tempLine = rawLine[x].Split(';'); for (int y = 0; y < tempLine.Length; y++) { DateTime hour = Convert.ToDateTime(tempLine[6]); for(int z=0; z<11; z++) { xlWorkSheet.Cells[y + 2, (z+1)] = tempLine[z]; } xlWorkSheet.Cells[y + 2, 12] = hour.Hour; xlWorkSheet.Cells[y + 2, 13] = tempLine[8] == "0" ? "SAME" : tempLine[9]; } Console.WriteLine("Current line = " + x + "\n"); }