/// <summary>
        /// Excel转换DataTable
        /// </summary>
        /// <param name="FilePath">文件的绝对路径</param>
        /// <returns>DataTable</returns>
        public static DataTable ExcelInput(string FilePath) 
        {
            //第一行一般为标题行。
            DataTable table = new DataTable();
            //根据路径通过已存在的excel来创建HSSFWorkbook,即整个excel文档
            HSSFWorkbook workbook = new HSSFWorkbook(File.Open(FilePath, FileMode.Open));
            HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(0);
            //获取excel的第一个sheet


            //获取Excel的最大行数
            int rowsCount = sheet.PhysicalNumberOfRows;
            //为保证Table布局与Excel一样,这里应该取所有行中的最大列数(需要遍历整个Sheet)。
            //为少一交全Excel遍历,提高性能,我们可以人为把第0行的列数调整至所有行中的最大列数。
            int colsCount = sheet.GetRow(0).PhysicalNumberOfCells;


            for (int i = 0; i < colsCount; i++)
            {
                table.Columns.Add(i.ToString());
            }

            for (int x = 0; x < rowsCount; x++)
            {
                DataRow dr = table.NewRow();
                for (int y = 0; y < colsCount; y++)
                {
                    dr[y] = sheet.GetRow(x).GetCell(y).ToString();
                }
                table.Rows.Add(dr);
            }

            sheet = null;
            workbook = null;
            return table;
        }

 

相关文章:

  • 2021-10-08
  • 2022-12-23
  • 2022-12-23
  • 2021-08-02
  • 2022-12-23
  • 2022-01-21
  • 2021-08-28
猜你喜欢
  • 2022-12-23
  • 2021-12-26
  • 2021-12-22
  • 2021-07-27
  • 2022-03-02
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案