• 将list输出成Excel到指定目录


                System.Data.DataTable dtSource = ToDataTable<EmpExtension>(empList);  //数据源
    
                context.Response.ContentType = "application/vnd.ms-excel";
                context.Response.ContentEncoding = Encoding.UTF8;
                context.Response.Charset = "UTF-8";
                context.Response.AppendHeader("Content-Disposition",
                    "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));  //路径:HttpUtility.UrlEncode(strFileName, Encoding.UTF8)
    
    
                HSSFWorkbook workbook = new HSSFWorkbook();
                HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();
    
                //填充表头
                HSSFRow dataRow = (HSSFRow)sheet.CreateRow(0);
                foreach (DataColumn column in dtSource.Columns)
                {
                    dataRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                }
    
    
                //填充内容
                for (int i = 0; i < dtSource.Rows.Count; i++)
                {
                    dataRow = (HSSFRow)sheet.CreateRow(i + 1);
                    for (int j = 0; j < dtSource.Columns.Count; j++)
                    {
                        dataRow.CreateCell(j).SetCellValue(dtSource.Rows[i][j].ToString());
                    }
                }
    
                using (MemoryStream ms = new MemoryStream())
                {
                    using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
                    {
                        workbook.Write(fs);
                    }
                    ms.Flush();
    
                    context.Response.BinaryWrite(ms.GetBuffer());
                }

    这里使用了NPOI,还有context可以使用HttpContext.Current代替。strFileName是自定义的路径

    另外,将list转化成DataTable的方法:

    public static DataTable ToDataTable<T>(List<T> items)
            {
                DataTable dataTable = new DataTable();
    
                PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
                foreach (PropertyInfo prop in Props)
                {
                    dataTable.Columns.Add(prop.Name);
                }
    
                foreach (T obj in items)
                {
                    var values = new object[Props.Length];
                    for (int i = 0; i < Props.Length; i++)
                    {
                        values[i] = Props[i].GetValue(obj, null);
                    }
                    dataTable.Rows.Add(values);
                }
    
                return dataTable;
            }
    记录编程的点滴,体会学习的乐趣
  • 相关阅读:
    POI使用详解
    POI导入导出Excel文件(二)
    jsp页面String转JSON
    jQuery的9中构造函数
    元素的BFC特性与自适应布局
    JS replace可以接受回调函数
    基于clip-path的任意元素的碎片拼接动效(源自鑫空间)
    解耦应用逻辑/事件处理程序
    CSS行高line-height的一些深入理解及应用
    常见的三种三栏网页宽度自适应布局 方法
  • 原文地址:https://www.cnblogs.com/AduBlog/p/14688475.html
Copyright © 2020-2023  润新知