コード例 #1
0
        public virtual DataTable GetData(Stream stream, string[] columnNames = null, bool isFirstColumn = false)
        {
            using (stream)
            {
                var sheet = _workBook.GetSheetAt(0);
                if (sheet != null)
                {
                    DataTable dt = new DataTable();
                    if (columnNames == null || columnNames.Length <= 0)
                    {
                        IRow headerRow   = sheet.GetRow(0);
                        int  columnCount = headerRow.Cells.Count;
                        columnNames = new string[columnCount];
                        for (int i = 0; i < columnCount; i++)
                        {
                            //判断第一行是否是列名,如果不是,系统自动生成列名
                            string columnName = "列" + i.ToString();
                            if (isFirstColumn)
                            {
                                object column = GetValue(headerRow.GetCell(i));
                                if (column != null || !string.IsNullOrEmpty(column.ToString()))
                                {
                                    columnName = column.ToString();
                                }
                            }
                            columnNames[i] = columnName;
                        }
                    }
                    //添加列
                    DataTableHelper.AddColumns(dt, columnNames);
                    var  row        = sheet.GetRowEnumerator();
                    bool isFirstRow = true;
                    while (row.MoveNext())
                    {
                        //如果第一行为标题,则添加数据的时候过滤
                        if (isFirstColumn && isFirstRow)
                        {
                            isFirstRow = false;
                            continue;
                        }
                        DataRow dtRow    = dt.NewRow();
                        IRow    excelRow = row.Current as IRow;
                        for (int i = 0; i < columnNames.Length; i++)
                        {
                            var cell = excelRow.GetCell(i);

                            if (cell != null)
                            {
                                dtRow[i] = GetValue(cell);
                            }
                        }
                        dt.Rows.Add(dtRow);
                    }
                    return(dt);
                }
            }

            return(null);
        }