/// <summary>
    /// Excel导入导出帮助类
    /// 记得引入 NPOI
    /// 下载地址   http://npoi.codeplex.com/releases/
    /// </summary>

public class ExcelHelper
    {
        #region 导出Excel

/// <summary>
        /// 导出Excel  注:model 字段必须加[DisplayName("XXX")]不要导出的标为[DisplayName("null")],并且不要导出的字段放在最后,要导出的放前面
        /// </summary>
        /// <param name="p_List">数据集合</param>
        /// <param name="p_Title">Excel路径</param>
        /// <param name="ColumnsCount">总列数</param>
        public void ToExcel<T>(List<T> p_List, string p_Title, int ColumnsCount)
        {
            if (p_List == null || p_List.Count <= 0 || ColumnsCount <= 0)
            {
                return;
            }
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));

if (properties.Count <= 0)
            {
                return;
            }

StringBuilder ExcelInfo = new StringBuilder();
            string sign = string.Empty;
            string DisplayName = string.Empty;
            //写表头
            for (int i = 0; i < ColumnsCount; i++)
            {
                DisplayName = properties[i].DisplayName;
                if (!string.IsNullOrEmpty(DisplayName) && DisplayName != "null" && DisplayName != "Id")
                {
                    sign = i == ColumnsCount - 1 ? "\n" : "\t";
                    ExcelInfo.AppendFormat("{0}{1}", DisplayName, sign);
                }
            }

//写表内容
            for (int i = 0; i < p_List.Count; i++)
            {
                for (int j = 0; j < ColumnsCount; j++)
                {
                    DisplayName = properties[j].DisplayName;
                    if (!string.IsNullOrEmpty(DisplayName) && DisplayName != "null" && DisplayName != "Id")
                    {
                        sign = j == ColumnsCount - 1 ? "\n" : "\t";
                        object obj = properties[j].GetValue(p_List[i]);
                        obj = obj == null ? string.Empty : obj.ToString();
                        ExcelInfo.AppendFormat("{0}{1}", obj, sign);
                    }
                }
            }

HttpResponse p_Response = HttpContext.Current.Response;
            p_Response.Clear();
            p_Response.ClearContent();
            p_Response.Buffer = true;

//设置Http的头信息,编码格式
            p_Response.AppendHeader("Content-Disposition", "attachment;filename=" + p_Title + ".xls");
            p_Response.ContentType = "application/ms-excel";

//设置编码
            p_Response.Charset = "gb2312";
            p_Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            p_Response.Write(ExcelInfo);
            p_Response.Flush();
            p_Response.Close();
            p_Response.End();
        }

#endregion

#region 导入Excel数据

/// <summary>
        /// OleDB连接Excel文件 --> DataSet
        /// </summary>
        /// <param name="xlsFilePath">.xls文件路径</param>
        /// <returns></returns>
        public static DataSet XlsToDataSet(string xlsFilePath)
        {
            OleDbConnection oleDBConn = new OleDbConnection();
            OleDbDataAdapter oleAdMaster = new OleDbDataAdapter();
            DataSet ds = new DataSet();

try
            {
                FileInfo file = new FileInfo(xlsFilePath);
                if (!file.Exists)
                {
                    throw new Exception("文件不存在。");
                }

string extension = file.Extension.ToLower();
                StringBuilder oleDBConnStr = new StringBuilder();
                switch (extension)
                {
                    case ".xls":
                        oleDBConnStr.AppendFormat("Provider=Microsoft.Jet.Oledb.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=NO;IMEX=1';", xlsFilePath);//此连接只能操作Excel2007之前(.xls)文件
                        //备注: "HDR=yes;"是说Excel文件的第一行是列名而不是数据,"HDR=No;"正好与前面的相反。
                        //      "IMEX=1 "如果列中的数据类型不一致,使用"IMEX=1"可必免数据类型冲突。
                        break;
                    case ".xlsx":
                        oleDBConnStr.AppendFormat("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';", xlsFilePath);
                        break;
                    default:
                        oleDBConnStr.AppendFormat("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;HDR=YES;IMEX=1;", xlsFilePath);
                        break;
                }

oleDBConn = new OleDbConnection(oleDBConnStr.ToString());
                oleDBConn.Open();

DataTable tableStructure = oleDBConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

if (tableStructure != null && tableStructure.Rows.Count > 0)
                {
                    tableStructure.TableName = tableStructure.Rows[0]["TABLE_NAME"].ToString();
                    StringBuilder sqlStr = new StringBuilder();
                    sqlStr.AppendFormat("select * from [{0}]", tableStructure.TableName);

oleAdMaster = new OleDbDataAdapter(sqlStr.ToString(), oleDBConn);
                    oleAdMaster.Fill(ds, "m_tableName");

if (ds.Tables["m_tableName"].Rows.Count <= 0)
                    {
                        throw new Exception("excel文件中没有有客户数据,请录入数据。");
                    }
                }
                else
                {
                    throw new Exception("未能找到该上传的excel文件。");
                }
            }
            finally
            {
                oleAdMaster.Dispose();
                oleDBConn.Close();
                oleDBConn.Dispose();
            }

return ds;
        }

#endregion

#region NPOI 导出Excel

private const Int32 MaxRowPerSheet = 65535;
        private Int32 rowPerSheet = 1000;
        public Int32 RowPerSheet
        {
            get { return rowPerSheet; }
            set
            {
                if (value < 0 || value > MaxRowPerSheet)
                {
                    throw new ArgumentOutOfRangeException("RowPerSheet");
                }
                else
                {
                    rowPerSheet = value;
                }
            }
        }

HSSFWorkbook hssfworkbook;

public void Export<T>(IList<T> records)
        {
            if (records.Count == 0)
                throw new ArgumentNullException("无导出数据。");

PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            int ColumnsCount = properties.Count;
            PropertyInfo[] props = new PropertyInfo[ColumnsCount];
            string DisplayName = string.Empty;
            for (int i = 0; i < ColumnsCount; i++)
            {
                DisplayName = properties[i].DisplayName;
                if (!string.IsNullOrEmpty(DisplayName) && DisplayName != "null" && DisplayName != "Id")
                {
                    props[i] = typeof(T).GetProperty(properties[i].Name); //注意属性数组仍然可以有元素为null
                }
            }

ISheet sheet = null;
            IRow row = null;

for (int r = 0; r < records.Count; r++)
            {
                if ((r % RowPerSheet) == 0)
                {
                    Int32 sheetIndex = (Int32)((Double)r / RowPerSheet) + 1;
                    sheet = hssfworkbook.CreateSheet("Sheet" + sheetIndex);
                    row = sheet.CreateRow(0);
                    for (int i = 0; i < ColumnsCount; i++)
                    {
                        DisplayName = properties[i].DisplayName;
                        if (!string.IsNullOrEmpty(DisplayName) && DisplayName != "null" && DisplayName != "Id")
                        {
                            row.CreateCell(i).SetCellValue(properties[i].DisplayName);
                        }
                    }
                    Console.WriteLine();
                }

//注意CreateRow(Int32 rownum)中参数rownum虽然从第0行开始,但因为表头存在,每次得往下一行
                row = sheet.CreateRow(r % RowPerSheet + 1);
                for (int i = 0; i < props.Length; i++)
                {
                    if (props[i] != null) //注意null检查
                    {
                        Object value = props[i].GetValue(records[r], null);
                        if (value != null)
                        {
                            row.CreateCell(i).SetCellValue(value.ToString());
                        }
                    }
                }
            }

for (Int32 i = 0; i < hssfworkbook.NumberOfSheets; i++)
            {
                sheet = hssfworkbook.GetSheetAt(i);
                for (Int32 h = 0; h < ColumnsCount; h++)
                {
                    sheet.AutoSizeColumn(h); //每列宽度自适应
                }
            }
        }

/// <summary>
        /// 导出Excel
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="records">数据</param>
        /// <param name="filename">Excel名称</param>
        public void SaveToExcel<T>(IList<T> records, string fileName)
        {
            RowPerSheet = 100;

string userAgent = HttpContext.Current.Request.ServerVariables["http_user_agent"].ToLower();
            if (userAgent.IndexOf("firefox") == -1)//判断是否是火狐浏览器
                fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);

HttpResponse p_Response = HttpContext.Current.Response;
            p_Response.ContentType = "application/vnd.ms-excel";
            p_Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName));
            p_Response.Clear();

InitializeWorkbook();
            Export<T>(records);
            GetExcelStream().WriteTo(p_Response.OutputStream);
            p_Response.End();
        }

MemoryStream GetExcelStream()
        {
            //Write the stream data of workbook to the root directory
            MemoryStream file = new MemoryStream();
            hssfworkbook.Write(file);
            return file;
        }

void InitializeWorkbook()
        {
            hssfworkbook = new HSSFWorkbook();

////create a entry of DocumentSummaryInformation
            DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            // dsi.Company = "NPOI Team";
            hssfworkbook.DocumentSummaryInformation = dsi;

////create a entry of SummaryInformation
            SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
            //  si.Subject = "NPOI SDK Example";
            hssfworkbook.SummaryInformation = si;
        }

#endregion

#region NPOI 导入Excel

/// <summary>
        /// Excel转换DataTable
        /// </summary>
        /// <param name="FilePath">文件的绝对路径</param>
        /// <returns>DataTable</returns>
        public static DataTable ExcelInput(string FilePath)
        {
            DataTable dt = new DataTable();

HSSFWorkbook hssfworkbook;
            using (FileStream file = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
            {
                hssfworkbook = new HSSFWorkbook(file);
            }
            ISheet sheet = hssfworkbook.GetSheetAt(0);
            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

IRow headerRow = sheet.GetRow(0);
            int cellCount = headerRow.LastCellNum;

for (int j = 0; j < cellCount; j++)
            {
                ICell cell = headerRow.GetCell(j);
                dt.Columns.Add(cell.ToString());
            }

for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
            {
                IRow row = sheet.GetRow(i);
                DataRow dataRow = dt.NewRow();

for (int j = row.FirstCellNum; j < cellCount; j++)
                {
                    if (row.GetCell(j) != null)
                        dataRow[j] = row.GetCell(j).ToString();
                }

dt.Rows.Add(dataRow);
            }
            return dt;
        }

#endregion
    }

Excel导入导出帮助类的更多相关文章

  1. 一个基于POI的通用excel导入导出工具类的简单实现及使用方法

    前言: 最近PM来了一个需求,简单来说就是在录入数据时一条一条插入到系统显得非常麻烦,让我实现一个直接通过excel导入的方法一次性录入所有数据.网上关于excel导入导出的例子很多,但大多相互借鉴. ...

  2. Java基础学习总结(49)——Excel导入导出工具类

    在项目的pom文件中引入 <dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifac ...

  3. java Excel导入导出工具类

    本文章,导入导出依赖提前定义好的模板 package com.shareworx.yjwy.utils; import java.io.File; import java.io.FileInputSt ...

  4. java中excel导入\导出工具类

    1.导入工具 package com.linrain.jcs.test; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import ...

  5. 【原创】POI操作Excel导入导出工具类ExcelUtil

    关于本类线程安全性的解释: 多数工具方法不涉及共享变量问题,至于添加合并单元格方法addMergeArea,使用ThreadLocal变量存储合并数据,ThreadLocal内部借用Thread.Th ...

  6. poi excel导入导出

    pom <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artif ...

  7. ASP.NET 之 常用类、方法的超级总结,并包含动态的EXCEL导入导出功能,奉上类库源码

    实用类:UtilityClass 包含如下方法 判断对象是否为空或NULL,如果是空或NULL返回true,否则返回false 验证手机号是否正确 13,15,18 验证邮箱 验证网址 MD5加密,返 ...

  8. 利用反射实现通用的excel导入导出

    如果一个项目中存在多种信息的导入导出,为了简化代码,就需要用反射实现通用的excel导入导出 实例代码如下: 1.创建一个 Book类,并编写set和get方法 package com.bean; p ...

  9. Excel导入导出的业务进化场景及组件化的设计方案(上)

    1:前言 看过我文章的网友们都知道,通常前言都是我用来打酱油扯点闲情的. 自从写了上面一篇文章之后,领导就找我谈话了,怕我有什么想不开. 所以上一篇的(下)篇,目前先不出来了,哪天我异地二次回忆的时候 ...

随机推荐

  1. lightoj 1017

    思路:动态规划,设dp[i][j]表示在前j个dusts中用了i刷子刷掉dusts的个数:状态转移方程就是: dp[i][j] = max(dp[i][j-1], dp[i-1][j-len[j]] ...

  2. 树-二叉平衡树AVL

    基本概念 AVL树:树中任何节点的两个子树的高度最大差别为1. AVL树的查找.插入和删除在平均和最坏情况下都是O(logn). AVL实现 AVL树的节点包括的几个组成对象: (01) key -- ...

  3. windows7 ubuntu双系统采用windows7 mbr引导方法

    在安装有Windows7系统上的机器,安装用Ubuntu后,开机会自动用grub2 引导.对于使用双系统的用户来说,用MBR和grub2都差不多,但是,我的机器上有三个系统,需要用MBR来引导变色龙, ...

  4. 【暑假】[深入动态规划]UVa 1628 Pizza Delivery

    UVa 1628 Pizza Delivery 题目: http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=51189 思路:    ...

  5. matlab 函数说明—ordfilt2

    今天看harris角点实现的源码,在某一个版本中看到了这个函数,不是很理解,doc ordfilt2之后还是不清楚,终于在matlab论坛上搞清楚了ordfilt2的功能.   中文理解函数名就是顺序 ...

  6. SGU132 - Another Chocolate Maniac(状态压缩DP)

    题目大意 给定一个N*M大小的大小的蛋糕,蛋糕的有些地方已经放置了东西,要求你在蛋糕上放入尽量少的1*2大小的巧克力,使得蛋糕不能够再放入巧克力 题解 和POJ1038恰好相反,此题是放入尽量少的巧克 ...

  7. 解决网站出错后 跳转 友好页面 的 asp .net 配置

    <system.webServer> <httpErrors errorMode="DetailedLocalOnly"> <remove statu ...

  8. 关于mac 80端口问题

    使用 maven启动 jettry时 ,jetty使用的是80端口 ,但是 mac 在1024以下的端口似乎是不让随便使用的. 在网上查了好多方式,其中的一种说是做端口转发,其实也就是把80转换成别的 ...

  9. Java网络编程(TCP服务端)

    /* * TCP服务端: * 1.创建服务端socket服务,并监听一个端口 * 2.服务端为了给客户端提供服务,获取客户端的内容,可以通过accept方法获取连接过来的客户端对象 * 3.可以通过获 ...

  10. 第十三章、学习 Shell Scripts 善用判断式

    善用判断式 利用 test 命令的测试功能 我要检查 /dmtsai 是否存在时,使用: [root@www ~]# test -e /dmtsai [root@www ~]# test -e /dm ...