ExcelHandle

using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;

namespace MVCStudy.Helper
{
    public class ExcelHandle
    {
        /// <summary> 
        /// 将DataTable数据导出到Excel文件中(xlsx) 
        /// </summary> 
        /// <param name="dt">数据源</param> 
        /// <param name="excelName">文件名称</param> 
        public static void TableToExcelForXLSX(DataTable dt, string excelName)
        {
            XSSFWorkbook xssfworkbook = new XSSFWorkbook();
            ISheet sheet = xssfworkbook.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());
                }
            }
            HttpContext curContext = HttpContext.Current;
            curContext.Response.Clear();
            curContext.Response.ContentType = "application/x-excel";
            string filename = HttpUtility.UrlEncode(excelName + DateTime.Now.ToString("yyyyMMddHHmm") + ".xlsx");
            curContext.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
            xssfworkbook.Write(curContext.Response.OutputStream);
            curContext.Response.End();
        }
        /// <summary>
        /// 读取excel(版本不低于2007)至DataTable
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static DataTable ExcelToTableForXLSX(string file)
        {
            DataTable dt = new DataTable();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                XSSFWorkbook xssfworkbook = new XSSFWorkbook(fs);
                ISheet sheet = xssfworkbook.GetSheetAt(0);
                //表头  
                IRow header = sheet.GetRow(sheet.FirstRowNum);
                List<int> columns = new List<int>();
                for (int i = 0; i < header.LastCellNum; i++)
                {
                    object obj = GetValueTypeForXLSX(header.GetCell(i) as XSSFCell);
                    if (obj == null || obj.ToString() == string.Empty)
                    {
                        dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                    }
                    else
                        dt.Columns.Add(new DataColumn(obj.ToString()));
                    columns.Add(i);
                }
                //数据  
                for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                {
                    DataRow dr = dt.NewRow();
                    bool hasValue = false;
                    foreach (int j in columns)
                    {
                        dr[j] = GetValueTypeForXLSX(sheet.GetRow(i).GetCell(j) as XSSFCell);
                        if (dr[j] != null && dr[j].ToString() != string.Empty)
                        {
                            hasValue = true;
                        }
                    }
                    if (hasValue)
                    {
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }

        /// <summary>  
        /// 获取单元格类型(xlsx)  
        /// </summary>  
        /// <param name="cell"></param>  
        /// <returns></returns>  
        private static object GetValueTypeForXLSX(XSSFCell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:  
                    return null;
                case CellType.Boolean: //BOOLEAN:  
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:  
                    return cell.NumericCellValue;
                case CellType.String: //STRING:  
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:  
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:  
                default:
                    return "=" + cell.CellFormula;
            }
        }

        /// <summary>
        /// 将List导出到Excel
        /// </summary>
        /// <param name="enList">List数据</param>
        /// <param name="fileName">Excel文件名</param>
        /// <param name="sheetName">Excel工作表名</param>
        /// <param name="cell0Value">首行提示信息</param>
        public void IListToExcel( IList enList, string fileName, string sheetName,string cell0Value)
        {
            IWorkbook workbook = new XSSFWorkbook();
            ISheet sheet = workbook.CreateSheet(sheetName);
            sheet.CreateRow(0).CreateCell(0).SetCellValue(cell0Value);
            List<string> Ihead = new List<string>();
            Type types = enList[0].GetType();
            foreach(var item in types.GetProperties())
            {
                Ihead.Add(item.Name);
            }
            IRow row1 = sheet.CreateRow(1);
            for (int i = 0; i < Ihead.Count; i++)
            {
                row1.CreateCell(i).SetCellValue(Ihead[i]);
            }
            int rowIndex = 2;
            foreach (var item in enList)
            {
                IRow rowTmp = sheet.CreateRow(rowIndex);
                for (int i = 0; i < Ihead.Count; i++)
                {
                    System.Reflection.PropertyInfo properotyInfo = item.GetType().GetProperty(Ihead[i]); // 属性的信息
                    object properotyValue = properotyInfo.GetValue(item, null);// 属性的值
                    string cellValue = properotyValue.ToString()??null;// 单元格的值
                    rowTmp.CreateCell(i).SetCellValue(cellValue);
                }
                rowIndex++;
            }
            using (FileStream file = new FileStream(fileName, FileMode.Create))
            {
                workbook.Write(file);
                file.Close();
            }
        }
    }
}

 

posted @ 2017-07-20 14:06  付旭洋  阅读(605)  评论(0编辑  收藏  举报