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

删除回忆录丶 提交于 2019-12-23 12:17:52

问题


I am trying to save a DataTable into an excel sheet.. my code is like this..

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[][].

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[][] ? Iterating through Excel, DataTable and assigning seems slower with bulk data..

Also I don't want to setup querying with DSN for excel.. I chose excel storage to avoid the configuring of any databases.. :P I found a detailed explanation of ways of writing data to excel here.. http://support.microsoft.com/kb/306023


回答1:


At last I used NPOI library for this. It is quite simple and free.

The code to convert DataTable to excel as follows.

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);
            }
        }


来源:https://stackoverflow.com/questions/11438587/convert-a-jagged-array-to-a-2d-array-directly-without-iterating-each-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!