惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
V2EX - 技术
V2EX - 技术
The Last Watchdog
The Last Watchdog
宝玉的分享
宝玉的分享
T
Tenable Blog
WordPress大学
WordPress大学
K
Kaspersky official blog
Microsoft Security Blog
Microsoft Security Blog
大猫的无限游戏
大猫的无限游戏
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Hacker News - Newest:
Hacker News - Newest: "LLM"
P
Palo Alto Networks Blog
Help Net Security
Help Net Security
V
Vulnerabilities – Threatpost
Know Your Adversary
Know Your Adversary
C
CXSECURITY Database RSS Feed - CXSecurity.com
A
Arctic Wolf
Forbes - Security
Forbes - Security
Microsoft Azure Blog
Microsoft Azure Blog
爱范儿
爱范儿
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
The Cloudflare Blog
Hugging Face - Blog
Hugging Face - Blog
H
Hacker News: Front Page
W
WeLiveSecurity
博客园 - 【当耐特】
G
Google Developers Blog
Martin Fowler
Martin Fowler
TaoSecurity Blog
TaoSecurity Blog
Hacker News: Ask HN
Hacker News: Ask HN
人人都是产品经理
人人都是产品经理
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
AI
AI
N
Netflix TechBlog - Medium
C
Cisco Blogs
I
Intezer
aimingoo的专栏
aimingoo的专栏
博客园 - 聂微东
G
GRAHAM CLULEY
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Apple Machine Learning Research
Apple Machine Learning Research
月光博客
月光博客
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
www.infosecurity-magazine.com
www.infosecurity-magazine.com
小众软件
小众软件
Blog — PlanetScale
Blog — PlanetScale
MyScale Blog
MyScale Blog
L
Lohrmann on Cybersecurity
Engineering at Meta
Engineering at Meta

博客园 - 衡斅

基于.net C# Socket WinForm MQTT 客户端开发 基于.Net C# 通信开发-网络调试助手 基于.Net C# 通信开发-串口调试助手 基于HBuilderX+UniApp+ColorUi+UniCloud 优宝库 开发实战(一) .net core 跨平台开发 微服务架构 基于Nginx反向代理 服务集群负载均衡 .Net Core 跨平台开发实战-服务器缓存:本地缓存、分布式缓存、自定义缓存 redis 分布式缓存实战-redis 事务 基于.net EF6 MVC5+WEB Api 的Web系统框架总结(3)-项目依赖注入 基于.net EF6 MVC5+WEB Api 的Web系统框架总结(2)-业务项目搭建 基于.net EF6 MVC5+WEB Api 的Web系统框架总结(1)-Web前端页面 基于html5 plus + Mui 移动App开发(三)-食全库 基于Html5 Plus + Vue + Mui 移动App开发(三)-文件操作(读取、保存、更新数据) 基于Html5 Plus + Vue + Mui 移动App 开发(二) 基于html5 plus + Mui 移动App开发(一) 基于百度地图的产品销售的单位查看功能设计与实现 实全软件产品自动升级管理解决方案 基于服务(Web Service)的文件管理Winform客户端实现(二) 如何通过WPS 2013 API 将Office(Word、Excel和PPT)文件转PDF文件 如何通过SerialPort读取和写入设备COM端口数据
基于.net EF6 MVC5+WEB Api 的Web系统框架总结(4)-Excel文件读、写操作
衡斅 · 2019-09-21 · via 博客园 - 衡斅

  Excel文件读、写可以使用Office自带的库(Microsoft.Office.Interop.Excel),前提是本机须安装office才能运行,且不同的office版本之间可能会有兼容问题。
还可以使用NPOI,在不安装office的时候也是可以读写的,速度很快。当然,还有支持Excel2007以上版本的OpenXml。以及其他一些开源项目,由于本人不太熟悉,在此不做过多介绍。
  为了解决烦人Office版本兼容问题,本项目-ShiQuan.Offices 决定采用基于NPOI,进行Excel文件读、写操作。
  本项目目前实现内容包括:
  1、直接根据DataTable,生成Excel文件内容。
  2、根据列表设置和DataTable,生成Excel文件内容。
  3、根据Excel模板,使用模板设置,生成Excel文件内容。
  4、读取Excel内容,返回DataTable。

  本项目基于LGPL3.0开源,供大家参考、使用,欢迎提供宝贵意见!
  项目源码:https://gitee.com/ShiQuanSoft/ShiQuan.Offices

  下面介绍分享如何使用该项目-ShiQuan.Offices。
  首先,创建ConsoleApp测试项目,添加程序包安装:

     

    1、先我们试下,普通的DataTable生成Excel文件是怎样的?

try
            {
                //取出数据源
                DataTable dtData = new DataTable();
                dtData.Columns.Add("account");
                dtData.Columns.Add("realname");
                dtData.Columns.Add("birthday");
                dtData.Columns.Add("description");
                dtData.Columns.Add("remark");

                DataRow dr = dtData.NewRow();
                dr["account"] = "账户";
                dr["realname"] = "姓名";
                dr["birthday"] = "2000-05-25";
                dr["description"] = "说明";
                dr["remark"] = "说明";/*多余字段,不会数据导出*/
                dtData.Rows.Add(dr);
                Console.WriteLine("生成2007以上版本Excel...");
                NPOIHelper.SaveToExcel(dtData, "XSSFWorkbook.xlsx");
                Console.WriteLine("生成2003版本Excel...");
                NPOIHelper.SaveToExcel(dtData, "HSSFWorkbook.xls");
            }
            catch (Exception ex)
            {
                Console.WriteLine("导出异常:" + ex.Message);
            }

  运行效果:

     

  2、一般从系统中导出Excel,我们都将采用中文标题,设置相应的数据列格式,对齐方式等信息?

try
            {
                //取出数据源
                DataTable dtData = new DataTable();
                dtData.Columns.Add("account");
                dtData.Columns.Add("realname");
                dtData.Columns.Add("gender");
                dtData.Columns.Add("birthday");
                dtData.Columns.Add("enabled");
                dtData.Columns.Add("price");
                dtData.Columns.Add("percent");
                dtData.Columns.Add("money");
                dtData.Columns.Add("remark");

                DataRow dr = dtData.NewRow();
                dr["account"] = "账户";
                dr["realname"] = "姓名";
                dr["gender"] = "0";/*0:女*/
                dr["birthday"] = "2000-05-25";
                dr["price"] = "10.5656";
                dr["percent"] = "0.56";
                dr["money"] = "1000.56";
                dr["enabled"] = "1";/*是否启用:1:是*/
                dr["remark"] = "说明";/*多余字段,不会数据导出*/
                dtData.Rows.Add(dr);
                /*设置导出格式*/
                ColumnCollection colModel = new ColumnCollection();
                colModel.Add("account", "账户");
                colModel.Add("realname", "姓名");
                colModel.Add("birthday", "出生日期", typeof(DateTime), "yyyy年MM月dd日");
                colModel.Add("price", "保留两位",typeof(double), "#0.00");
                colModel.Add("percent", "百分比", typeof(double), "0.00%");
                colModel.Add(new ColumnModel() { Name = "money", Desc = "货币格式", Type = typeof(double), Format = "¥#,##0", TextAlign = ColumnAlign.Right });
                colModel.Add("gender", "性别", new DataOptions("0:女,1:男".Split(',')));
                colModel.Add(new ColumnModel[]
                {
                    new ColumnModel() { Name = "enabled", Desc = "是否启用", Options = new DataOptions("0:否,1:是".Split(',')), TextAlign = ColumnAlign.Center }
                });

                Console.WriteLine("保存Excel...");
                //调用导出方法
                NPOIHelper.SaveToExcel(dtData,colModel, "用户信息.xls");
                Console.WriteLine("Excel保存成功!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("导出异常:" + ex.Message);
            }

  运行效果:

       

  3、当我们使用普通的设置数据列格式,还不能满足要求时,此时,只能采用预定的Excel模板,使用数据填充方式,生成Excel文件?

var fileName = "根据模板生成Excel.xlsx";
            try
            {
                var templateFile = "templateFile.xlsx";
                System.IO.File.WriteAllBytes(templateFile, ConsoleApp.Properties.Resources.template);

                List<TemplateModel> list = new List<TemplateModel>();
                list.Add(new TemplateModel() { RowIndex = 1, ColIndex = 0, Value = "账号" });
                list.Add(new TemplateModel() { RowIndex = 1, ColIndex = 1, Value = "名称" });
                list.Add(new TemplateModel() { RowIndex = 1, ColIndex = 2, Value = "2000-09-01" });
                list.Add(new TemplateModel() { RowIndex = 1, ColIndex = 3, Value = "备注" });

                list.Add(new TemplateModel() { RowIndex = 2, ColIndex = 0, Value = "账号" });
                list.Add(new TemplateModel() { RowIndex = 3, ColIndex = 1, Value = "名称" });
                list.Add(new TemplateModel() { RowIndex = 4, ColIndex = 2, Value = "2000-09-01" });
                list.Add(new TemplateModel() { RowIndex = 5, ColIndex = 3, Value = "备注" });
                Console.WriteLine("根据模板生成Excel...");
                NPOIHelper.SaveToExcel(templateFile,"sheet1", list, fileName);
                Console.WriteLine("Excel保存成功!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("生成异常:" + ex.Message);
            }

  定义的模板:

  

       运行效果:

  

  4、生成Excel文件方法介绍完毕,下面我们看下怎么读取Excel文件内容,我们以直接读取模板生成的Excel文件为例?

try
            {
                
                Console.WriteLine("读取Excel内容...");
                DataTable dtData = NPOIHelper.ReadToTable(fileName);
                StringBuilder fileContent = new StringBuilder();
                //标题
                foreach (DataColumn dc in dtData.Columns)
                {
                    fileContent.Append(dc.ColumnName + "\t");
                }
                fileContent.AppendLine();

                foreach (DataRow dr in dtData.Rows)
                {
                    foreach (DataColumn dc in dtData.Columns)
                    {
                        if (dr[dc.ColumnName] == DBNull.Value)
                            fileContent.Append("\t");
                        else
                            fileContent.Append(dr[dc.ColumnName].ToString() + "\t");
                    }
                    fileContent.AppendLine();
                }
                Console.WriteLine("文件内容:");
                Console.WriteLine(fileContent.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine("生成异常:" + ex.Message);
            }

  运行效果:

  
  

至此 ShiQuan.Offices Excel文件读、写操作项目介绍分享完毕,欲听更多精彩,且听下回分解!