zoukankan      html  css  js  c++  java
  • 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();
                }
            }
        }
    }
  • 相关阅读:
    对象数组化 Object.values(this.totalValueObj).forEach(value => {
    禅道
    Ant Design Ant Design 实战教程(beta 版) 在 model 中请求服务端数据
    react 环境搭建
    返回运行方法,可以写在一行 callback&&callback()
    computed 里面 不能写箭头函数 都要写 function () {} 否则页面会都不显示
    webStorm -> Version Control _> Repository -> Filter By User 查看svn日志
    created:异步初始化数据都应该放到 created里面
    收藏夹
    keep-alive 必须 页面有name 要不缓存不住数据
  • 原文地址:https://www.cnblogs.com/fuxuyang/p/7210930.html
Copyright © 2011-2022 走看看