Npoi导出excel整理(附源码)

前些日子做了一个简单的winform程序,需要导出的功能,刚开始省事直接使用微软的组件,但是导出之后发现效率极其低下,绝对像web那样使用npoi组件,因此简单的进行了整理,包括直接根据DataTable导出excel及DataGridview导出excel,版本是1.2.4,下面贴下主要代码两种方式,1、NPOI导出excel、 2、普通的导出excel

下面贴下主要代码:NPOI导出

复制代码
     /// <summary>/// DataTable导出到Excel文件/// </summary>/// <param name="dtSource">源DataTable</param>/// <param name="strHeaderText">表头文本</param>/// <param name="strFileName">保存位置</param>public static void DataTableToExcel(DataTable dtSource, string strHeaderText, string strFileName){using (MemoryStream ms = DataTableToExcel(dtSource, strHeaderText)){using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write)){byte[] data = ms.ToArray();fs.Write(data, 0, data.Length);fs.Flush();}}}/// <summary>/// DataTable导出到Excel的MemoryStream/// </summary>/// <param name="dtSource">源DataTable</param>/// <param name="strHeaderText">表头文本</param>public static MemoryStream DataTableToExcel(DataTable dtSource, string strHeaderText){HSSFWorkbook workbook = new HSSFWorkbook();HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();#region 右击文件 属性信息{DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();dsi.Company = "NPOI";workbook.DocumentSummaryInformation = dsi;SummaryInformation si = PropertySetFactory.CreateSummaryInformation();si.Author = "文件作者信息"; //填加xls文件作者信息si.ApplicationName = "创建程序信息"; //填加xls文件创建程序信息si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息si.Comments = "作者信息"; //填加xls文件作者信息si.Title = "标题信息"; //填加xls文件标题信息si.Subject = "主题信息";//填加文件主题信息si.CreateDateTime = System.DateTime.Now;workbook.SummaryInformation = si;}#endregionHSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle();HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat();dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");//取得列宽int[] arrColWidth = new int[dtSource.Columns.Count];foreach (DataColumn item in dtSource.Columns){arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;}for (int i = 0; i < dtSource.Rows.Count; i++){for (int j = 0; j < dtSource.Columns.Count; j++){int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;if (intTemp > arrColWidth[j]){arrColWidth[j] = intTemp;}}} int rowIndex = 0; foreach (DataRow row in dtSource.Rows){#region 新建表,填充表头,填充列头,样式if (rowIndex == 65535 || rowIndex == 0){if (rowIndex != 0){sheet = (HSSFSheet)workbook.CreateSheet();}#region 表头及样式{HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);headerRow.HeightInPoints = 25;headerRow.CreateCell(0).SetCellValue(strHeaderText);HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();//  headStyle.Alignment = CellHorizontalAlignment.CENTER;HSSFFont font = (HSSFFont)workbook.CreateFont();font.FontHeightInPoints = 20;font.Boldweight = 700;headStyle.SetFont(font);headerRow.GetCell(0).CellStyle = headStyle;// sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));//headerRow.Dispose();}#endregion#region 列头及样式{HSSFRow headerRow = (HSSFRow)sheet.CreateRow(1); HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();//headStyle.Alignment = CellHorizontalAlignment.CENTER;HSSFFont font = (HSSFFont)workbook.CreateFont();font.FontHeightInPoints = 10;font.Boldweight = 700;headStyle.SetFont(font); foreach (DataColumn column in dtSource.Columns){headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);headerRow.GetCell(column.Ordinal).CellStyle = headStyle;//设置列宽sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); }// headerRow.Dispose();}#endregionrowIndex = 2;}#endregion#region 填充内容HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);foreach (DataColumn column in dtSource.Columns){HSSFCell newCell =(HSSFCell) dataRow.CreateCell(column.Ordinal);string drValue = row[column].ToString();switch (column.DataType.ToString()){case "System.String"://字符串类型newCell.SetCellValue(drValue);break;case "System.DateTime"://日期类型System.DateTime dateV;System.DateTime.TryParse(drValue, out dateV);newCell.SetCellValue(dateV);newCell.CellStyle = dateStyle;//格式化显示break;case "System.Boolean"://布尔型bool boolV = false;bool.TryParse(drValue, out boolV);newCell.SetCellValue(boolV);break;case "System.Int16"://整型case "System.Int32":case "System.Int64":case "System.Byte":int intV = 0;int.TryParse(drValue, out intV);newCell.SetCellValue(intV);break;case "System.Decimal"://浮点型case "System.Double":double doubV = 0;double.TryParse(drValue, out doubV);newCell.SetCellValue(doubV);break;case "System.DBNull"://空值处理newCell.SetCellValue("");break;default:newCell.SetCellValue("");break;}}#endregionrowIndex++;} using (MemoryStream ms = new MemoryStream()){workbook.Write(ms);ms.Flush();ms.Position = 0;sheet.Dispose();//workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheetreturn ms;} }
复制代码

普通excel导出

复制代码
#region 导出excelpublic static void ExportExcel(string fileName, DataGridView myDGV,bool isShowDialog){string saveFileName = "";if (isShowDialog){//bool fileSaved = false;SaveFileDialog saveDialog = new SaveFileDialog();saveDialog.DefaultExt = "xls";saveDialog.Filter = "Excel文件|*.xls";saveDialog.FileName = fileName;saveDialog.ShowDialog();saveFileName = saveDialog.FileName;if (saveFileName.IndexOf(":") < 0) return; //被点了取消 }else{// saveFileName = Application.StartupPath + @"\导出记录\" + fileName + ".xls";saveFileName = fileName;}Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();if (xlApp == null){MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");return;}Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 //写入标题for (int i = 0; i < myDGV.ColumnCount; i++){worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;}//写入数值for (int r = 0; r < myDGV.Rows.Count; r++){for (int i = 0; i < myDGV.ColumnCount; i++){if (myDGV[i, r].ValueType == typeof(string)|| myDGV[i, r].ValueType == typeof(DateTime))//这里就是验证DataGridView单元格中的类型,如果是string或是DataTime类型,则在放入缓 存时在该内容前加入" ";{worksheet.Cells[r + 2, i + 1] = "'" + myDGV.Rows[r].Cells[i].Value;}else{worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;}}System.Windows.Forms.Application.DoEvents();}worksheet.Columns.EntireColumn.AutoFit();//列宽自适应//if (Microsoft.Office.Interop.cmbxType.Text != "Notification")//{//    Excel.Range rg = worksheet.get_Range(worksheet.Cells[2, 2], worksheet.Cells[ds.Tables[0].Rows.Count + 1, 2]);//    rg.NumberFormat = "00000000";//}if (saveFileName != ""){try{workbook.Saved = true;workbook.SaveCopyAs(saveFileName);//fileSaved = true;}catch (Exception ex){//fileSaved = false;MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);}}//else//{//    fileSaved = false;//}xlApp.Quit();GC.Collect();//强行销毁 // if (fileSaved && System.IO.File.Exists(saveFileName)) System.Diagnostics.Process.Start(saveFileName); //打开EXCELMessageBox.Show(fileName + "保存成功", "提示", MessageBoxButtons.OK);}#endregion
复制代码

5万条数据性能测试

下面附上源码,里面有NPOI和普通导出excel的性能比较。

下载源码 如果您觉的文章不错,请点击推荐!

转载于:https://www.cnblogs.com/amylis_chen/p/8462215.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/390163.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

44. 通配符匹配

44. 通配符匹配 给定一个字符串 (s) 和一个字符模式 &#xff0c;实现一个支持 ‘?’ 和 ‘*’ 的通配符匹配。 ? 可以匹配任何单个字符。 * 可以匹配任意字符串&#xff08;包括空字符串&#xff09;。 两个字符串完全匹配才算匹配成功。说明: s 可能为空&#xff0c;且…

递归javascript_使用freeCodeCamp挑战解释了JavaScript中的递归

递归javascriptIn this article I will touch on a few important ideas to help you understand Recursion in JavaScript. I’m not going to give a full definition here, but you can take a look at what Wikipedia has to say. 在本文中&#xff0c;我将介绍一些重要的想…

入库成本与目标成本对比报表中我学到的东西

1、SQL方面&#xff1a; &#xff08;1&#xff09;、用DECODE函数解决除数为零的情况 具体语法&#xff1a; DECODE&#xff08;参数&#xff0c;0&#xff0c;1&#xff0c;参数&#xff09; ->DECODE(TAB1.A8&#xff0c;0&#xff0c;1&#xff0c;TAB1.A8) &#xff08…

J - Borg Maze

J - Borg Maze 思路&#xff1a;bfs最小生成树。#include<queue> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #define MAXN 110 using namespace std; int fa[MAXN]; struct nond{int x,y,z; }v[MAXN*MAXN]; s…

1095. 山脉数组中查找目标值

1095. 山脉数组中查找目标值 &#xff08;这是一个 交互式问题 &#xff09; 给你一个 山脉数组 mountainArr&#xff0c;请你返回能够使得 mountainArr.get(index) 等于 target 最小 的下标 index 值。 如果不存在这样的下标 index&#xff0c;就请返回 -1。 何为山脉数组…

【小摘抄】关于C++11下 string各类用法(持续更新)

http://blog.csdn.net/autocyz/article/details/42391155 提供了最简单的详解 下列对本人近期开发中的一些心得体会进行摘抄 1.string按照字符进行截取 示例代码&#xff1a; string teststring "#12313#kajlkfdsa";//通讯消息示例&#xff0c;结合string的内置函数…

sql综合练习题

一、表关系 年级表&#xff1a;class_grade create table class_grade(gid int primary key auto_increment,gname varchar(20) not null); insert into class_grade(gname) values(一年级),(二年级),(三年级); 班级表&#xff1a;class create table class(cid int primary ke…

javascript原型_在JavaScript中冻结原型时会发生什么

javascript原型Have you wondered what happens when you freeze the prototype of an object? Lets find out together.您是否想过冻结对象的原型时会发生什么&#xff1f; 让我们一起找出答案。 对象 (Objects) In JavaScript, objects are dynamic collections of propert…

迟来的2017总结

明天就是年后第一天上班了&#xff08;过年期间请了6天假&#xff09;&#xff0c; 打算今天写一下2017的总结&#xff0c;本来还想写2018的愿景的&#xff0c;不过想想还是算了&#xff0c;现在没什么想法&#xff0c;不想敷衍了事。 先贴一个2017的提升计划&#xff1a; http…

tomcat启动卡住

新部署的项目启动tomcat后一直停在org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.16&#xff0c;卡在了org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/opt/tomcat/web…

怎样准备阿里技术面试_如何准备技术面试

怎样准备阿里技术面试In June 2020 I watched an inspiring talk by Anthony D. Mays, a technical coach and founder at Morgan Latimerco. He came on a Facebook Developer Circles Benin live session and talked about how to prepare for a technical interview. 2020年…

通过一个简单例子理解 RecyclerView.ItemDecoration

一、前言 RecyclerView 是从5.0推出的 MD 风格的控件。RecyclerView 之前有 ListView、GridView&#xff0c;但是功能很有限&#xff0c;例如 ListView 只能实现垂直方向上的滑动等。但是存在则合理&#xff0c;ListView 却没有被官方标记为 Deprecated&#xff0c;有兴趣的同学…

Entity Framework Logging and Intercepting Database Operations (EF6 Onwards)

参考官方文档&#xff1a;https://msdn.microsoft.com/en-us/library/dn469464(vvs.113).aspx转载于:https://www.cnblogs.com/liandy0906/p/8473110.html

面试题 17.14. 最小K个数

面试题 17.14. 最小K个数 设计一个算法&#xff0c;找出数组中最小的k个数。以任意顺序返回这k个数均可。 示例&#xff1a; 输入&#xff1a; arr [1,3,5,7,2,4,6,8], k 4 输出&#xff1a; [1,2,3,4] 提示&#xff1a; 0 < len(arr) < 1000000 < k < min(1…

这是您现在可以免费获得的115张Coursera证书(在冠状病毒大流行期间)

At the end of March, the world’s largest Massive Open Online Course provider Coursera announced that they are offering 100 free courses in response to the impact of the COVID-19 pandemic. 3月底&#xff0c;全球最大的大规模在线公开课程提供商Coursera 宣布 &a…

由浅入深理解----java反射技术

java反射机制详解 java反射机制是在运行状态下&#xff0c;对任意一个类可以获取该类的属性和方法&#xff0c;对任意一个对象可以调用其属性和方法。这种动态的获取信息和调用对象的方法的功能称为java的反射机制 class<?>类&#xff0c;在java.lang包下面&#xff0c;…

【VMware vSAN 6.6】5.5.Update Manager:vSAN硬件服务器解决方案

目录 1. 简介 1.1.适用于HCI的企业级存储2. 体系结构 2.1.带有本地存储的服务器2.2.存储控制器虚拟系统套装的缺点2.3.vSAN在vSphere Hypervisor中自带2.4.集群类型2.5.硬件部署选项3. 启用vSAN 3.1.启用vSAN3.2.轻松安装3.3.主动测试4. 可用性 4.1.对象和组件安置4.2.重新构建…

5848. 树上的操作

给你一棵 n 个节点的树&#xff0c;编号从 0 到 n - 1 &#xff0c;以父节点数组 parent 的形式给出&#xff0c;其中 parent[i] 是第 i 个节点的父节点。树的根节点为 0 号节点&#xff0c;所以 parent[0] -1 &#xff0c;因为它没有父节点。你想要设计一个数据结构实现树里面…

了解如何通过Python使用SQLite数据库

SQLite is a very easy to use database engine included with Python. SQLite is open source and is a great database for smaller projects, hobby projects, or testing and development.SQLite是Python附带的非常易于使用的数据库引擎。 SQLite是开源的&#xff0c;是用于…

32位JDK和64位JDK

32位和64位系统在计算机领域中常常提及&#xff0c;但是仍然很多人不知道32位和64位的区别&#xff0c;所以本人在网上整理了一些资料&#xff0c;并希望可以与大家一起分享。对于32位和64位之分&#xff0c;本文将分别从处理器&#xff0c;操作系统&#xff0c;JVM进行讲解。 …