Excel 数据导入到DataTable

Posted SmilePastaLi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Excel 数据导入到DataTable相关的知识,希望对你有一定的参考价值。

excel 2003,2007导入到datatable

技术分享
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;

namespace Siia.CarParts.UI.Common
{
    public class ExcelHelper
    {
        public class x2003
        {
            #region Excel 2003导入
            public static DataTable ImportExcelFile(string filePath)
            {
                try
                {
                    using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);
                        NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);

                        System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
                        DataTable dt = new DataTable();
                        for (int j = 0; j < (sheet.GetRow(0).LastCellNum); j++)
                        {
                            dt.Columns.Add(Convert.ToChar(((int)A) + j).ToString());
                        }
                        while (rows.MoveNext())
                        {
                            HSSFRow row = (HSSFRow)rows.Current;
                            DataRow dr = dt.NewRow();
                            for (int i = 0; i < row.LastCellNum; i++)
                            {
                                NPOI.SS.UserModel.ICell cell = row.GetCell(i);
                                if (cell == null)
                                {
                                    dr[i] = null;
                                }
                                else
                                {
                                    dr[i] = cell.ToString();
                                }
                            }
                            dt.Rows.Add(dr);
                        }
                        return dt;
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            #endregion
        }

        public class x2007
        {
            #region Excel 2007导入
            public static DataTable ImportExcelFile(string filePath)
            {
                try
                {
                    using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        XSSFWorkbook xssfworkbook = new XSSFWorkbook(file);
                        NPOI.SS.UserModel.ISheet sheet = xssfworkbook.GetSheetAt(0);
                        System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
                        DataTable dt = new DataTable();
                        for (int j = 0; j < (sheet.GetRow(0).LastCellNum); j++)
                        {
                            dt.Columns.Add(Convert.ToChar(((int)A) + j).ToString());
                        }
                        while (rows.MoveNext())
                        {
                            XSSFRow row = (XSSFRow)rows.Current;
                            DataRow dr = dt.NewRow();
                            for (int i = 0; i < row.LastCellNum; i++)
                            {
                                NPOI.SS.UserModel.ICell cell = row.GetCell(i);
                                if (cell == null)
                                {
                                    dr[i] = null;
                                }
                                else
                                {
                                    dr[i] = cell.ToString();
                                }
                            }
                            dt.Rows.Add(dr);
                        }
                        return dt;
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            #endregion
        }
        /// <summary>
        ///  将Excel数据导入到DataTable中(xls,xlsx)
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public static DataTable GetDataTable(string filepath)
        {
            var dt = new DataTable("xls");
            if (filepath.Last() == s)
            {
                dt = x2003.ImportExcelFile(filepath);
            }
            else
            {
                dt = x2007.ImportExcelFile(filepath);
            }
            return dt;
        }

        /// <summary>
        /// 将DataTable数据导出到Excel文件中(xls)
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="file"></param>
        public static void TableToExcelForXLS(DataTable dt, string file)
        {
            HSSFWorkbook hssfworkbook = new HSSFWorkbook();
            ISheet sheet = hssfworkbook.CreateSheet("Test");

            //表头
            IRow row = sheet.CreateRow(0);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ICell cell = row.CreateCell(i);
                cell.SetCellValue(dt.Columns[i].ColumnName);
            }

            //数据
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                IRow row1 = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    ICell cell = row1.CreateCell(j);
                    cell.SetCellValue(dt.Rows[i][j].ToString());
                }
            }

            //转为字节数组
            MemoryStream stream = new MemoryStream();
            hssfworkbook.Write(stream);
            var buf = stream.ToArray();

            //保存为Excel文件
            using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                fs.Write(buf, 0, buf.Length);
                fs.Flush();
            }
        }
    }
}
View Code

 

以上是关于Excel 数据导入到DataTable的主要内容,如果未能解决你的问题,请参考以下文章

导入excel把数据存在datatable中,用sqlbulkcopy把datable批量导入到数据库的表中

Excel 数据导入到DataTable

C# 导入Excel数据到Datatable 在本地调试时没问题,上传到服务器就报错。

解决从Excel导入数据库,导入到DataTable时数据类型发生变化的问题(如数字类型变成科学计数法,百分数变成小数)

如何快速的将 DataTable 导入到 Excel 中 ?

Excel 导入到Datatable 中,再使用常规方法写入数据库