.Net List<T>数据集转Excel

.net / .net core excel转pdf 方法1,调用Microsoft.Office.Interop.Excel,缺点是需要安装excel,不支持.net core private static bool ExcelToPdfWithExcel(string excelFile, string pdfFile) { Microsoft.Office.Interop.Excel.Applicat... 阅读详情

方法一:添加对Microsoft.Office.Interop.Excel的引用

  /// <summary>
        /// 将List保存为Excel文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName"></param>
        /// <param name="data"></param>
        public static void ExportsListToExcel<T>( List<T> data,string fileName)
        {
            if (data != null)
            {
                // 创建Excel应用程序对象
                Application excApp = new Application();
                Workbook workBook = excApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
                Worksheet workSeet = workBook.Worksheets[1]; //取得sheet1
                Range range = null;
                int tableCount = data.Count;//数据总记录数量
                var type = typeof(T);
                var properties = type.GetProperties();
                //Excel列名称
                for (int i = 0; i < properties.Length; i++)
                {
                    workSeet.Cells[1, i + 1] = properties[i].Name;

                    //设置标题的样式
                    range = (Range)workSeet.Cells[1, i + 1];
                    //range.Font.Bold = true; //粗体
                    range.Font.Size = "12";//字体大小
                    range.Font.Name = "宋体";
                    range.HorizontalAlignment = XlHAlign.xlHAlignCenter; //居中
                    range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, null); //背景色
                    range.EntireColumn.AutoFit(); //自动设置列宽
                    range.EntireRow.AutoFit(); //自动设置行高
                }
                //处理数据记录
                for (int r = 0; r < data.Count; r++)
                {
                    for (int c = 0; c < properties.Length; c++)
                    {
                        //写入内容
                        workSeet.Cells[r + 2, c + 1] = "'" + properties[c].GetValue(data[r]);
                        //设置样式
                        range = (Range)workSeet.Cells[r + 2, c + 1];
                        range.Font.Size = 9; //字体大小
                        range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, null); //加边框
                        range.EntireColumn.AutoFit(); //自动调整列宽
                    }
                }
                range.Borders[XlBordersIndex.xlInsideHorizontal].Weight = XlBorderWeight.xlThin;
                if (data.Count > 1)
                {
                    range.Borders[XlBordersIndex.xlInsideVertical].Weight = XlBorderWeight.xlThin;
                }
                try
                {
                    workBook.Saved = true;
                    workBook.SaveCopyAs(fileName);
                }
                catch
                {
                }
                workBook.Close();
                if (excApp != null)
                {
                    excApp.Workbooks.Close();
                    excApp.Quit();
                    int generation = GC.GetGeneration(excApp);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(excApp);
                    excApp = null;
                    GC.Collect(generation);
                }
                #region 强行杀死最近打开的Excel进程
                System.Diagnostics.Process[] excelProc = System.Diagnostics.Process.GetProcessesByName("EXCEL");
                System.DateTime startTime = new DateTime();
                int m, killID = 0;
                for (m = 0; m < excelProc.Length; m++)
                {
                    if (startTime < excelProc[m].StartTime)
                    {
                        startTime = excelProc[m].StartTime;
                        killID = m;
                    }
                }
                if (excelProc.Length > 0)
                {
                    if (excelProc[killID].HasExited == false)
                    {
                        excelProc[killID].Kill();
                    }
                }
                #endregion
            }
        }

方法二

/// <summary>
        /// 将List保存为Excel文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <param name="fileName"></param>
        /// <param name="ignoreColumnList">不需要的数据列</param>
        public static void ListToCsv<T>(List<T> data, string fileName, List<string> ignoreColumnList)
        {
            string title = "";
            try
            {
                FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate);
                StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default);
                var type = typeof(T);
                var properties = type.GetProperties();
                //Excel列名称
                for (int i = 0; i < properties.Length; i++)
                {
                    if (ignoreColumnList.Contains(properties[i].Name))
                        continue;
                    title += properties[i].Name + "\t"; //栏位:自动跳到下一单元格
                }
                title = title.Substring(0, title.Length - 1) + "\n";
                sw.Write(title);
                for (int r = 0; r < data.Count; r++)
                {
                    string line = "";
                    for (int c = 0; c < properties.Length; c++)
                    {
                        if (ignoreColumnList.Contains(properties[c].Name))
                            continue;
                        line += properties[c].GetValue(data[r]) + "\t"; //内容:自动跳到下一单元格

                    }
                    line = line.Substring(0, line.Length - 1) + "\n";
                    sw.Write(line);
                }
                sw.Close();
                fs.Close();
            }
            catch
            {

            }
        }

方法三

使用NPOI生成Excel

 /// <summary>
        /// List转Excel
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <param name="columnList"></param>
        /// <param name="fileRelativePath">返回的相对路径</param>
        public static bool ExportToExcel<T>(List<T> data, List<string> columnList, out string fileRelativePath)
        {
            string rootPath = AppDomain.CurrentDomain.BaseDirectory.Replace(@"\", @"/");
            string uploadFilePath = ConfigurationManager.AppSettings["FilePath"].ToString();
            if (string.IsNullOrWhiteSpace(uploadFilePath))
            {
                uploadFilePath = "/UploadFiles";
            }
            string filePath = "";
            filePath = rootPath.Substring(0, rootPath.LastIndexOf("/")) + uploadFilePath + "/ExcelFiles/";
            CreatePath(filePath);
            try
            {
                HSSFWorkbook hssfworkbook = new HSSFWorkbook();//初始化文件
                ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
                //单元格样式
                ICellStyle cellStyle = hssfworkbook.CreateCellStyle();
                cellStyle.Alignment = HorizontalAlignment.Center;
                cellStyle.BorderTop = BorderStyle.Thin;
                cellStyle.BorderLeft = BorderStyle.Thin;
                cellStyle.BorderRight = BorderStyle.Thin;
                cellStyle.BorderBottom = BorderStyle.Thin;
                //create a font style
                IFont font = hssfworkbook.CreateFont();
                font.FontHeight = 10 * 20;
                cellStyle.SetFont(font);
                var type = typeof(T);
                var properties = type.GetProperties();
                IRow firstrow = sheet1.CreateRow(0);//第一行,列名称
                int colIndex = 0;//列
                //第一列默认为序号列
                ICell cellNo = firstrow.CreateCell(colIndex);
                cellNo.SetCellValue("序号");
                cellNo.CellStyle = cellStyle;
                colIndex++;
                //Excel列名称
                for (int i = 0; i < properties.Length; i++)
                {
                    if (!columnList.Contains(properties[i].Name))
                        continue;
                    var displayName = properties[i].GetCustomAttribute<DisplayNameAttribute>();
                    ICell cell = firstrow.CreateCell(colIndex);
                    if (displayName != null)
                    {
                        //firstrow.CreateCell(colIndex).SetCellValue(displayName.DisplayName);
                        cell.SetCellValue(displayName.DisplayName);
                    }
                    else
                    {
                        cell.SetCellValue(properties[i].Name);
                    }
                    cell.CellStyle = cellStyle;
                    colIndex++;
                }
                //设置列宽
                for (int n = 0; n < colIndex; n++)
                {
                    sheet1.SetColumnWidth(n, 4000);
                }
                for (int i = 0; i < data.Count; i++)
                {
                    colIndex = 0;
                    IRow row = sheet1.CreateRow(i + 1);
                    //第一列序号列
                    ICell cellSort = row.CreateCell(colIndex);
                    cellSort.SetCellValue(i + 1);
                    cellSort.CellStyle = cellStyle;
                    colIndex++;
                    for (int j = 0; j < properties.Length; j++)
                    {
                        if (!columnList.Contains(properties[j].Name))
                            continue;
                        Type propertyType = properties[j].PropertyType;//获取数据类型
                        string cellValue = "";
                        if (propertyType == typeof(DateTime) || propertyType == typeof(DateTime?))
                        {
                            if (properties[j].GetValue(data[i]) != null)
                            {
                                cellValue = Convert.ToDateTime(properties[j].GetValue(data[i])).ToString("yyyy-MM-dd");
                            }
                        }
                        else
                        {
                            if (properties[j].GetValue(data[i]) != null)
                            {
                                cellValue = properties[j].GetValue(data[i]).ToString();
                            }
                        }
                        //row.CreateCell(colIndex).SetCellValue(cellValue);
                        ICell cell = row.CreateCell(colIndex);
                        cell.SetCellValue(cellValue);
                        cell.CellStyle = cellStyle;
                        colIndex++;
                    }
                }
                string fileName = Guid.NewGuid().ToString() + ".xls";
                filePath = filePath + fileName;
                FileStream file = new FileStream(filePath, FileMode.Create);
                hssfworkbook.Write(file);
                file.Close();
                fileRelativePath = "/" + filePath.Replace(rootPath, "");
                return true;
            }
            catch (Exception ex)
            {
                fileRelativePath = "";
                return false;
            }
        }

 

VB.NET 导出数据到EXCEL中 ----------VB.NET 导出数据到EXCEL中-------------  在引用当中引入Microsoft Excel 11.0 Object Library        Dim oExcel As New Excel.Application        Dim obook As Excel.Workbook        Dim oSheet As Excel.Workshe 阅读详情

相关推荐

VB.NET结合EXCEL统计生产报表

Untitled Document<!-- -->             VB.NET结合EXCEL统计生产报表          —企业信息化探讨之二          屠恩海    开发工具:Microsoft Visual Studio .NET 2003    操作系统:Windows XP

2066的专栏 2398

.net list导出到excel

//创建工作表 ISheet sheet = workbook.CreateSheet("onesheet"); IRow row0 = sheet.CreateRow(0);//制作标题(字段) row0.CreateCell(0).SetCellValue("ProductName"); ...

qq_37573226的博客 718

C#将list和DataTable中的数据导出到Excel的功能

C#将list和DataTable中的数据导出到Excel的功能

开发指南009-从list导出excel文件

从数据库返回一般是对象的列表,平台底层提供了从list转为excel文件的方法。平台的设计思想就是为一些典型的场景设计对应的解决方法,通过模式化的方法来简化编程和提高维护性(通过标准化来减少学习成本和维护成本,张三做的东西和李四做的东西模式一样)基本模式就是填充ExportOfListVO,然后调用ExcelUtil.exportExcel。field对应数据对象的数据属性。

wangbing1125的博客 527

.net导出数据到excel

一个.net将数据导出到excel的源码,用反射机制导出List<T>到excel,也可将DataTable导出到excel,样式可以灵活修改

RS485 MODBUS转PROFINET网关案例丨汇川变频器接入到1200 PROFINET

本案例介绍的是用北京小疆智控(北京)技术有限公司生产的GW-PN5003型MODBUS RTU转PROFINET网关将汇川变频器接入西门子PLC1200 PROFINET网络的使用方法。

bjxjzk的博客 1900

【.NET】C# List导出为Excel方法

/// <summary> /// list导出为Excel /// </summary> /// <param name="list"></param> /// <param name="filePath"></param> public static void DataExport<T>(List<T> list...

W's play ground 2756

手把手教你用fusb302实现PD快充:从驱动移植到实战调试(附源码)

本文详细解析了基于FUSB302芯片实现USB PD快充的完整开发流程。内容涵盖芯片选型、硬件设计要点、Linux驱动移植与内核集成,并重点剖析了PD协议交互中的关键调试技巧,如“死亡15ms”时序问题与中断模式选择。文章通过实战经验,帮助嵌入式开发者高效完成从驱动移植到系统集成的全链路开发,并附有源码参考。

sky77的博客 381

.NET导出Excel的四种方法及评测

.NET导出Excel的四种方法及评测 导出Excel是.NET的常见需求,开源社区、市场上,都提供了不少各式各样的Excel操作相关包。本文,我将使用NPOI、EPPlus、OpenXML、Aspose.Cells四个市面上常见的库,各完成一个导出Excel示例。然后对其代码风格和性能做一个横向比较。最后我将说出我自己的感想。 文中所有的示例代码可以在这里下载: https://git...

weixin_30335353的博客 1748

Arduino DHT11 ESP8266 在OneNet云平台上读取 温湿度

#include "ESP8266.h" #include "dht11.h" #include "SoftwareSerial.h" #define SSID "540ND" #define PASSWORD "" #define HOST_NAME "api.heclouds.com" #define DEVICE_ID "" #define HOST_PORT (80) String APIKey = " "; #define INTER

weixin_45852947的博客 2432

用废旧汽车电池DIY家用UPS:手把手教你低成本搭建Wi-Fi不断电系统

本文详细介绍了如何利用废旧汽车电池DIY低成本家用UPS系统,确保Wi-Fi设备在断电时持续供电。通过精选材料、电路搭建和安全防护,实现高效稳定的电源转换与智能切换,成本仅为市售UPS的三分之一。特别适合家庭办公和远程工作者提升网络供电可靠性。

weixin_29200485的博客 471

C#.net core导出List<T>中的数据到Excel,以及获取实体类的描述[Description(“xx“)],和参数名,生成表头list

直接上代码 第一个方法ToObjectListExcel,传入数据list和表头list<ExportField>,ExportField在后面,还有一个string类型的路径名,可以随意,用于生成文件夹 /// <summary> ///List object 转 Excel /// </summary> /// <param name="list"> 数据</param> /

小星博博的博客 1573

uniCloud云存储进阶:七牛云扩展存储从开通、绑定域名到批量上传的完整实战

本文详细介绍了uniCloud云存储进阶实践,重点讲解如何通过七牛云扩展存储实现从开通、绑定域名到批量上传的完整流程。内容涵盖成本优势分析、域名备案方案、SSL证书配置、多文件并发上传控制等实战技巧,并提供可直接复用的代码示例,帮助开发者高效构建内容社区类应用。

weixin_26985923的博客 473

Excel导入SQL(VB.NET版)

强烈推荐一个大神的人工智能的教程:http://www.captainbed.net/zhanghan 【前言】 我们从第一次机房就开始接触了数据库内容导出到Excel,机房重构的时候同样遇到了,做过VB版的也做过VB.NET版的(其实两者并没有多大差别)。考试导数据的时候用过一次将Excel导入到数据库,当时并没有深入的去想是怎么导进去的。 【内容】 ●窗体展示 ...

至尊宝 2万+

告别重复劳动:用Python+pywinauto打造你的微信个人助理(自动回复/收款/定时发消息)

本文介绍如何利用Python和pywinauto库构建微信个人助手,实现自动回复、定时消息、智能收款等功能,告别重复劳动。通过详细的代码示例和配置指南,帮助开发者快速掌握微信自动化技术,提升工作效率。

weixin_42568801的博客 339

网络层隧道技术之ICMP隧道(pingTunnel/IcmpTunnel)

目录 ICMP隧道 使用ICMP搭建隧道(PingTunnel) 使用ICMP搭建隧道(Icmptunnel) ICMP隧道 ICMP隧道简单实用,是一个比较特殊的协议。在一般的通信协议里,如果两台设备要进行通信,肯定需要开放端口,而在ICMP协议下就不需要。最常见的ping命令就是利用的ICMP协议,攻击者可以利用命令行得到比回复更多的ICMP请求。在通常情况下,每个ping命令都有相...

谢公子的博客 6714

.Net Epplus读取excel转List<T>

在.net中说到对excel的读取大家首先想到的可能是NPOI、LinqToExcel,最近在项目中用到Epplus,觉得也不错。Epplus可以在NuGet中安装我想达到的效果是导入Excel,直接转成想要的泛型集合。我有个Person的类public class Person { public string Name { get; set; } public int Age {...

hbxixi20549的博客 3304

保研考研机试攻略(满分篇):第二章——满分之路上(1)

保研考研机试攻略(满分篇):第二章——满分之路上(1)2.1计算机和基础+2.2进阶背包问题+2.3毛毛虫算法

qq_63349644的博客 1200

.NET操作Excel COM对象

多年来 COM 对象一直是 Windows 编程的基础,然而随着技术的进步和发展,微软推出了更佳出色的.NET。.NET Framework 提供了一个称为公共语言运行库的运行时环境(CLR),它的托管执行过程,自动的内存管理,以及在版本的控制上都较COM技术有很大的提高。可以预见的是,.NET 平台应用程序将最终取代那些用 COM 开发的应用程序。但不可避免的是,在向.NET过渡时,我们还是需要

Lullaby's Blog 3万+

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

ASP.net转Excel

using System;using System.Data;using Excel;namespace XmlTest{ ///  /// Class1 的摘要说明。 ///  public class Class1 {  public Class1(DataView dv,string str)  {   //   // TODO: 在此处添加构造函数逻辑   //   Excel.A

DigJim的专栏 1892

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

ASP.NET的网站NPOI转EXCEL,转DataTable

using System; using System.Web; using System.Text; using System.Data; using System.IO; using NPOI.XSSF.UserModel; using NPOI.SS.UserModel; namespace Admin.Common {     public class Common

VictorZhang 1085

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

【.NET 开发】通过 C# 实现 Excel 转 JSON

本文介绍使用免费 .NET 库实现 Excel 到 JSON 的自动化转换。实现流程为:加载 Excel 文件→读取工作表→导出 DataTable→JSON 序列化→保存结果。

Eiceblue的专栏 906

三种方法让.NET轻松实现Excel转PDF

前一段时间有网友问Excel转pdf怎么转pdf,小编帮他实现了一个,方法是使用EPPlus和PdfSharp组件实现,由于依赖OfficeOpenXml他也没有用上,后来小编又实现了二种不依赖OfficeOpenXml的方法。此方法跟Spire一样默认不支持中文,需要我们单独引用中文字库,方法GetChineseFont就是处理引用中文字库。标签作为表格的开始。此方法需要注意的是Spire默认不支持中文,需要我们单独引用中文字库,在代码的13行就是引用字库的地方,大家可以把字库拷贝到自己的项目引用。

软件开发学习交流 1214

Excel-DNA如何让.NET开发者为Excel注入强大功能?

Excel-DNA是一个免费开源的.NET集成框架,专为Excel用户和开发者设计,让你能够使用C#、VB.NET等.NET语言为Excel创建自定义函数、菜单和工具栏。如果你正在寻找一种比VBA更强大、比传统COM插件更简单的方法来扩展Excel功能,Excel-DNA正是你需要的解决方案。 ## 🔥 核心价值:为什么选择Excel-DNA? ### 超越VBA的性能与功能 你是否曾因VB

gitblog_00161的博客 1029

【.Net码农】【NPOI】NPOI对Excel的操作(Sheet转DataTable、List<T>)

http://www.cnblogs.com/dedeyi/p/3240592.html NPOI对Excel的操作(Sheet转DataTable、List) 通过NPOI对Excel进行操作,这里主要是读取的操作。封装到ExcelHelper操作类中。 using System.Collections.Generic; using NPOI.H

能看代码的CrackLibby 1451

poi excel转html图片不展示_.NET版Spire.XLS v10.3新版来啦!一起回顾Excel格式转换教程指南...

Spire.XLS for .NET是一款专业的 .NET Excel 组件, 它可以用在各种 .NET 框架中,包括 .NET Core、ASP.NET 和 Windows Forms 等相关的 .NET 应用程序。Spire.XLS for .NET 提供了一个对象模型 Excel API,使开发人员可以快速地在 .NET 平台上完成对 Excel 的各种编程操作,如根据模板创建新的 Exce...

weixin_39559382的博客 285
上一篇: .NET base64与文件互转方法、 byte[]与文件互转方法
下一篇: .Net WebAPI FormData 上传文件实现
蓝晶之心
博客等级 码龄14年 273粉丝 198原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值