• 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
  • 相关阅读:
    sql server 2008数据复制方法
    排错技能:任务管理器中追踪某w3wp.exe是哪个IIS站点的application pool
    SplendidCRM中给来自EditView中的listbox控件设置选中值或数据源
    jQuery String Functions
    [转]jquery getJSON 数据联动(采用序列化和反序列化获取数据) .
    [转]javascript eval函数解析json数据时为什加上圆括号eval("("+data+")")
    深入理解C语言
    Qt回忆录之配置开发环境
    360电话面试
    浅谈C++设计模式之单例模式
  • 原文地址:https://www.cnblogs.com/SmilePastaLi/p/6860572.html
Copyright © 2020-2023  润新知