往Excel写入数据的方法比较多,但实际应用场景及对性能的要求决定了需要对方法有所取舍。一些具体情形和方法可以参见https://blog.csdn.net/u013109267/article/details/52651647?locationNum=2&fps=1
但受到.Net framework及Excel版本的影响,一些比较旧的方法不再有效。比如上面网页中快速写入的关键方法get_Range和set_Value在新的VSTO环境中就受到影响。但原帖中的思路跟方法是可以借鉴的:
//将Table数据转换成Array private object[,] Table2Array(System.Data.DataTable myTable) { int rowCount = myTable.Rows.Count; int colCount = myTable.Columns.Count; object[,] myArray = new object[rowCount, colCount]; for (int i = 0; i < rowCount; i++) { var row = myTable.Rows[i]; for(int j = 0; j < colCount; j++) { myArray[i][j] = row[j]; } return myArray; } //数据快速写入到Excel private void FastLoad(string sheetName, System.Data.DataTable myTable, int startX, int startY) { int rowCount = myTable.Rows.Count; int colCount = myTable.Columns.Count; object[,] myArray = Table2Array(myTable); //输出列名 for(int i = 0; i < colCount; i++) { Worksheets[sheetName].Cells[startX, startY + i] = myTable.Columns[i].ColumnName; } //数据输出到Excel Range range = Worksheets[sheetName].Range(Worksheets[sheetName].Cells[startX + 1, startY], Worksheets[sheetName].Cells[startX + rowCount, startY + colCount - 1]); range.Value2 = myArray; }
原文地址:https://www.cnblogs.com/RobZH/p/10014563.html
时间: 2024-10-28 21:31:07