简体   繁体   English

将锯齿状数组直接转换为2D数组而不迭代每个项目?

[英]Convert a jagged array to a 2D array directly without iterating each item?

I am trying to save a DataTable into an excel sheet.. my code is like this.. 我正在尝试将DataTable保存到Excel工作表中..我的代码是这样的..

Excel.Range range = xlWorkSheet.get_Range("A2");
range = range.get_Resize(dtExcel.Rows.Count, dtExcel.Columns.Count);
object[,] rng1 = new object[dtExcel.Rows.Count, dtExcel.Columns.Count];

Excel range requires range value as array[,] but I have the DataTable as jagged array[][]. Excel范围需要范围值作为数组[,]但我将DataTable作为锯齿数组[] []。

object[][] rng2 = dtExcel.AsEnumerable().Select(x => x.ItemArray).ToArray();

Is there any built-in function to directly convert the jagged array[][] to a 2D array[][] ? 是否有任何内置函数可以将锯齿状数组[] []直接转换为2D数组[] []? Iterating through Excel, DataTable and assigning seems slower with bulk data.. 通过Excel迭代,DataTable和分配对于批量数据来说似乎更慢。

Also I don't want to setup querying with DSN for excel.. I chose excel storage to avoid the configuring of any databases.. :PI found a detailed explanation of ways of writing data to excel here.. http://support.microsoft.com/kb/306023 此外,我不想设置使用DSN查询excel ..我选择了excel存储以避免配置任何数据库..:PI找到了有关将数据写入excel的方法的详细说明.. http:// support。 microsoft.com/kb/306023

At last I used NPOI library for this. 最后我为此使用了NPOI库 It is quite simple and free. 它非常简单而且免费。 the code to convert DataTable to excel as follows. 将DataTable转换为excel的代码如下。

HSSFWorkbook hssfworkbook = new HSSFWorkbook();
        foreach (DataTable dt in DataSource.Tables)
        {
            ISheet sheet1 = hssfworkbook.CreateSheet(dt.TableName);

            //Set column titles
            IRow headRow = sheet1.CreateRow(0); 
            for (int colNum = 0; colNum < dt.Columns.Count; colNum++)
            {
                ICell cell = headRow.CreateCell(colNum);
                cell.SetCellValue(dt.Columns[colNum].ColumnName);
            }

            //Set values in cells
            for (int rowNum = 1; rowNum <= dt.Rows.Count; rowNum++)
            {
                IRow row = sheet1.CreateRow(rowNum);
                for (int colNum = 0; colNum < dt.Columns.Count; colNum++)
                {
                    ICell cell = row.CreateCell(colNum);
                    cell.SetCellValue(dt.Rows[rowNum - 1][colNum].ToString());
                }
            }

            // Resize column width to show all data
            for (int colNum = 0; colNum < dt.Columns.Count; colNum++)
            {
                sheet1.AutoSizeColumn(colNum);
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM