将数组列表导入Excel格式,而无需在C#中使用for循环 [英] Import Array list to excel format with out using for loop in C#
问题描述
例如我的列表中有大量数据,我使用for循环完成了它.但是需要花费更多时间将数据导入excel.我尝试了下面的代码,没有使用for循环.但是我低于range.set_Value的错误.
E.g. I have huge number of data in my list, I done it using for loop. But taking more time to import the data into excel. I tried below code with out using for loop. But i'm getting below error in range.set_Value.
错误:类型的未处理异常mscorlib.dll中发生了'System.Runtime.InteropServices.COMException'附加信息:HRESULT异常:0x800A03EC
Error:An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll Additional information: Exception from HRESULT: 0x800A03EC
List<myobj> NGDetailsList = new List<myobj>();
NGDetailsList.Add(new myobj { name = "AAA", designation = "test" });
NGDetailsList.Add(new myobj { name = "BBB", designation = "test1" });
Microsoft.Office.Interop.Excel.Application PcInfoFile;
Microsoft.Office.Interop.Excel.Workbook workbook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
PcInfoFile = new Microsoft.Office.Interop.Excel.Application();
PcInfoFile.Visible = false;
PcInfoFile.Visible = true;
workbook = PcInfoFile.Workbooks.Open(@"C:\Users\AAAA\Desktop\New Microsoft Excel Worksheet.xlsx");
xlWorkSheet = workbook.Worksheets.get_Item(1);
// Get dimensions of the 2-d array
int rowCount = 2;
int columnCount = 2;
// Get an Excel Range of the same dimensions
Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
range = range.get_Resize(rowCount, columnCount);
// Assign the 2-d array to the Excel Range
range.set_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault, NGDetailsList);
推荐答案
找到了答案,现在一切正常.解决方案:使用2D数组代替列表.
Found the answers and now it is working fine. Solution : Used 2D array instead of list.
object[,] values = new object[5,4];
// row, column on worksheet
values[0, 0] = 11;
values[0, 1] = 12;
values[0, 2] = 13;
values[1, 0] = 21;
values[1, 1] = 22;
values[1, 2] = 23;
values[2, 0] = 31;
values[2, 1] = 32;
values[2, 2] = 32;
values[3, 0] = 41;
values[3, 1] = 42;
values[3, 2] = 42;
values[4, 0] = 51;
values[4, 1] = 52;
values[4,2] = 52;
range.set_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault, values);
这篇关于将数组列表导入Excel格式,而无需在C#中使用for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!