码迷,mamicode.com
首页 > 其他好文 > 详细

Excel 数据导入到DataTable

时间:2017-05-16 13:04:59      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:ide   tar   toe   ret   creates   str   文件中   art   add   

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

标签:ide   tar   toe   ret   creates   str   文件中   art   add   

原文地址:http://www.cnblogs.com/SmilePastaLi/p/6860572.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!