C# Excel 导入两种方式

  • 第一种导入 需要用到Microsoft.Jet.OLEDB.4.0或者Microsoft.ACE.OLEDB.12.0驱动 如果我没记错的话 如果是BS程序 部署的服务器上有驱动即可  如果CS程序则需要安装程序的客户端有该驱动

        ///

        /// 解析EXCEL文件

        ///

        /// FilePath">

        ///

        public System.Data.DataSet GetExcelData(string FilePath)

        {

            try

            {

                //利用ADO.NET读取Excel信息

                System.Data.DataSet myDataSet = new System.Data.DataSet();

                OleDbConnection myConn = new OleDbConnection();

                if (FilePath.EndsWith("xls") || FilePath.EndsWith("XLS"))

                {

                    myConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FilePath + ";Extended Properties='Excel 8.0;IMEX=1' ";

                }

                else if (FilePath.EndsWith("xlsx") || FilePath.EndsWith("XLSX"))

                {

                    myConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + FilePath + "; Extended Properties='Excel 12.0 Xml;IMEX=1'";

                }

                else

                {

                    return null;

                }

                myConn.Open();

                System.Data.DataTable SheetNamedt = myConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                if (SheetNamedt != null)

                {

                    foreach (System.Data.DataRow Row in SheetNamedt.Rows)

                    {

                        string strCom = " SELECT * FROM [" + Row["TABLE_NAME"].ToString() + "] ";

                        OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);

                        myCommand.Fill(myDataSet, "[" + Row["TABLE_NAME"].ToString() + "]");

                        myConn.Close();

                    }

                }

                else

                {

                    return null;

                }

                return myDataSet;

            }

            catch (Exception getException)

            {

                throw new ApplicationException(getException.Message);

            }

        }

 

 

. 第二种 NPOI   在程序里面添加NPOI程序包, 手动添加 或者在程序包控制台 执行Install-Package NPOI

///

 

        /// excel导入到datatable 

        ///

 

        /// filePath">excel路径 

        /// isColumnName">第一行是否是列名 

        /// 返回datatable 

        public DataSet ExcelToDataTable(string filePath, bool isColumnName)

        {

            DataSet dataSet = new DataSet();

            DataTable dataTable = null;

            FileStream fs = null;

            DataColumn column = null;

            DataRow dataRow = null;

            IWorkbook workbook = null;

            ISheet sheet = null;

            IRow row = null;

            ICell cell = null;

            int startRow = 0;

            try

            {

                using (fs = File.OpenRead(filePath))

                {

                    // 2007版本 

                    if (filePath.IndexOf(".xlsx") > 0)

                        workbook = new XSSFWorkbook(fs);

                    // 2003版本 

                    else if (filePath.IndexOf(".xls") > 0)

                        workbook = new HSSFWorkbook(fs);

 

                    if (workbook != null)

                    {

                        for (int sheetCount = 0; sheetCount < workbook.NumberOfSheets; sheetCount++)

                        {

                            //读取第一个sheet,当然也可以循环读取每个sheet 

                            sheet = workbook.GetSheetAt(sheetCount);

                            dataTable = new DataTable();

                            dataTable.TableName = sheet.SheetName;

                            if (sheet != null)

                            {

                                //总行数 

                                int rowCount = sheet.LastRowNum;

                                if (rowCount > 0)

                                {

                                    //第一行 

                                    IRow firstRow = sheet.GetRow(0);

                                    //列数 

                                    int cellCount = firstRow.LastCellNum;

 

                                    //构建datatable的列 

                                    if (isColumnName)

                                    {

                                        //如果第一行是列名,则从第二行开始读取 

                                        startRow = 1;

                                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)

                                        {

                                            cell = firstRow.GetCell(i);

                                            if (cell != null)

                                            {

                                                if (cell.StringCellValue != null)

                                                {

                                                    column = new DataColumn(cell.StringCellValue);

                                                    dataTable.Columns.Add(column);

                                                }

                                            }

                                        }

                                    }

                                    else

                                    {

                                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)

                                        {

                                            column = new DataColumn("column" + (i + 1));

                                            dataTable.Columns.Add(column);

                                        }

                                    }

 

                                    //填充行 

                                    for (int i = startRow; i <= rowCount; ++i)

                                    {

                                        row = sheet.GetRow(i);

                                        if (row == null) continue;

 

                                        dataRow = dataTable.NewRow();

                                        for (int j = row.FirstCellNum; j < cellCount; ++j)

                                        {

                                            if (j > 8)

                                            {

                                                break;

                                            }

                                            cell = GetCell(row, j);

                                            if (cell == null)

                                            {

                                                dataRow[j] = "";

                                            }

                                            else

                                            {

                                                cell.SetCellType(CellType.String);

                                                //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,) 

                                                switch (cell.CellType)

                                                {

                                                    case CellType.Blank:

                                                        dataRow[j] = "";

                                                        break;

                                                    case CellType.Numeric:

                                                        short format = cell.CellStyle.DataFormat;

                                                        //对时间格式(2015.12.52015/12/52015-12-5等)的处理 

                                                        if (format == 14 || format == 31 || format == 57 || format == 58)

                                                            dataRow[j] = cell.DateCellValue;

                                                        else

                                                            dataRow[j] = cell.NumericCellValue;

                                                        break;

                                                    case CellType.String:

                                                        dataRow[j] = cell.StringCellValue;

                                                        break;

                                                }

                                            }

                                        }

                                        dataTable.Rows.Add(dataRow);

                                    }

                                }

                            }

                            dataSet.Tables.Add(dataTable);

                        }

                    }

                }

                return dataSet;

            }

            catch (Exception ex)

            {

                if (fs != null)

                {

                    fs.Close();

                }

                return null;

            }

        }

 

        ///

        /// 单元格未被激活时,使用此方法获取单元格(作用于第一种方式有些单元格读取不出来,或者在一个excel中一列数据中的数据格式不是一样导致的部分单元格读取不出来的情况)

        ///

        /// row">

        /// index">

        ///

        public ICell GetCell(IRow row, int index)

        {

            ICell cell = row.FirstOrDefault(n => n.ColumnIndex == index);

            if (cell == null)

            {

                cell = row.CreateCell(index);

            }

            cell.SetCellType(CellType.String);

            return cell;

        }

你可能感兴趣的:(C#)