C# Excel To DataTable


原地址忘了

需引用NPOI,引用方法:項目引用那兒右鍵 => 管理NuGet程序包 => 游覽 =>輸入NPOI =>選中NPOI后安裝(一般是第一個)

 

/// <summary>
/// Excel 轉換為 Datatable
/// </summary>
/// <param name="sheetNum">工作表索引</param>
/// <param name="isFirstRowColumn">首行為列</param>
/// <param name="fileName">Excel文件路徑</param>
/// <returns></returns>
public DataTable ExcelToDataTable(int sheetNum, bool isFirstRowColumn, string fileName)
{
    IWorkbook workbook = null;
    ISheet sheet = null;
    DataTable myTable = new DataTable();
    try
    {
        var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        if (fileName.IndexOf(".xlsx") > 0)
            workbook = new XSSFWorkbook(fs);
        else if (fileName.IndexOf(".xls") > 0)
            workbook = new HSSFWorkbook(fs);
        sheet = workbook.GetSheetAt(sheetNum);

        //工作表不能為空
        if (sheet == null)
        {
            string str = "";
            for (int i = 0; i < workbook.NumberOfSheets; i++)
            {
                str += workbook.GetSheetAt(i).SheetName + ",";
            }
            str = workbook.NumberOfSheets + str;
            throw new Exception($"sheet不能為空!參數:{sheetNum} 工作簿信息:{str}");
        }

        //Excel最大列數
        int MaxColumnNum = 0;
        for (int i = 0; i < sheet.LastRowNum; i++)
        {
            var row = sheet.GetRow(i);
            if (row.LastCellNum > MaxColumnNum)
            {
                MaxColumnNum = row.LastCellNum;
            }
        }
        //Excel行數
        int MaxRowNum = sheet.LastRowNum;

        //table新增列
        for (int i = 0; i < MaxColumnNum; ++i)
        {
            //首行為列
            if (isFirstRowColumn)
            {
                bool addEmptyCell = true;//是否添加空列
                ICell cell = sheet.GetRow(0).GetCell(i);
                if (cell != null)
                {
                    //table列賦值
                    string cellValue = "";//列名
                    if (cell.CellType == CellType.Numeric)
                    {
                        cellValue = cell.NumericCellValue.ToString();
                    }
                    else
                    {
                        cellValue = cell.StringCellValue;
                    }
                    if (!string.IsNullOrWhiteSpace(cellValue))
                    {
                        //列數據為Excel的數據
                        addEmptyCell = false;
                        myTable.Columns.Add(new DataColumn(cellValue));
                    }
                }
                if (addEmptyCell)
                {
                    myTable.Columns.Add(new DataColumn(""));//列數據為空
                }
            }
            else
            {
                myTable.Columns.Add(new DataColumn(i + ""));
            }
        }

        //起始行
        int startRow = 0;
        if (isFirstRowColumn)
        {
            startRow = 1;
        }

        //DataTable賦值
        for (int i = startRow; i <= MaxRowNum; ++i)
        {
            IRow row = sheet.GetRow(i);
            if (row == null) continue;

            DataRow NewRow = myTable.NewRow();
            for (int j = row.FirstCellNum; j < row.LastCellNum; ++j)
            {
                ICell cell = row.GetCell(j);
                string value = "";
                if (cell != null)
                {
                    //table行賦值                            
                    if (cell.CellType == CellType.Numeric)
                    {
                        value = cell.NumericCellValue.ToString();
                        if ((j == 0) && ((i == 6) || (i == 12)))
                        {
                            //特殊的幾個單元格 轉換為 日期格式
                            value = ToDateTimeValue(cell.NumericCellValue.ToString());
                        }
                    }
                    else
                    {
                        //row.GetCell(j).SetCellType(CellType.String);
                        value = cell.StringCellValue;
                    }
                }
                NewRow[j] = value;
            }
            myTable.Rows.Add(NewRow);
        }
        return myTable;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM