DataTable to Excel(使用NPOI、EPPlus将数据表中的数据读取到excel格式内存中)
/// <summary>
/// DataTable to Excel(将数据表中的数据读取到excel格式内存中)
/// </summary>
/// <param name="dataTable">数据表</param>
/// <param name="excelType">excel格式</param>
/// <param name="sheetName">excel工作表名称</param>
/// <returns>内存流数据</returns>
public static Stream DataTableToExcel(DataTable dataTable, string excelType = ".xlsx", string sheetName = "sheet1")
{
Stream stream;
try
{
//根据excel文件类型创建excel数据结构
switch (excelType)
{
case ".xlsx":
stream = DataTableToExcelXlsx(dataTable, sheetName);
break;
case ".xls":
stream = DataTableToExcelXls(dataTable, sheetName);
break;
default:
stream = null;
break;
}
}
catch (Exception ex)
{
throw ex;
}
return stream;
}
2007版本使用EPPlus创建excel内存数据
/// <summary>
/// DataTable to Excel2007(将数据表中的数据读取到excel格式内存中)
/// </summary>
/// <param name="dataTable">数据表</param>
/// <param name="sheetName">excel工作表名称</param>
/// <returns>内存流数据</returns>
public static Stream DataTableToExcelXlsx(DataTable dataTable, string sheetName)
{
try
{
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add(sheetName);
ws.Cells["A1"].LoadFromDataTable(dataTable, true);
MemoryStream ms = new MemoryStream();
pck.SaveAs(ms);
ms.Flush();
ms.Position = ;//指定当前流的位置从0开始
return ms;
}
}
catch (Exception ex)
{
throw ex;
}
}
97-2003版本使用NPOI创建excel内存数据
/// <summary>
/// DataTable to Excel97-2003(将数据表中的数据读取到excel格式内存中)
/// </summary>
/// <param name="dataTable">数据表</param>
/// <param name="sheetName">excel工作表名称</param>
/// <returns>内存流数据</returns>
public static Stream DataTableToExcelXls(DataTable dataTable, string sheetName)
{
try
{
const int startIndex = ;
var fields = dataTable.Columns;
//创建excel数据结构
var workbook = new HSSFWorkbook();
//创建excel工作表
var sheet = workbook.CreateSheet(sheetName);
sheet.DefaultRowHeight = * ;
#region 创建标题行
var row = sheet.CreateRow(startIndex);
var headStyle = GetHeadStyle(workbook);
foreach (DataColumn column in dataTable.Columns)
{
var cellIndex = fields.IndexOf(column) + startIndex;
var cell = row.CreateCell(cellIndex);
cell.SetCellValue(column.ColumnName);
cell.CellStyle = headStyle;
sheet.AutoSizeColumn(cellIndex);
}
#endregion
#region 创建数据行
int rowIndex = ;
foreach (DataRow dataRow in dataTable.Rows)
{
row = sheet.CreateRow(rowIndex + );
foreach (DataColumn column in dataTable.Columns)
{
var cellIndex = fields.IndexOf(column) + startIndex;
var dataStyle = GetDataStyle(workbook);
var cell = row.CreateCell(cellIndex);
cell.CellStyle = dataStyle;
var value = dataRow[column.ColumnName];
switch ((value ?? string.Empty).GetType().Name.ToLower())
{
case "int32":
case "int64":
case "decimal":
dataStyle.Alignment = HorizontalAlignment.RIGHT;
cell.SetCellValue(ZConvert.To<double>(value, ));
break;
default:
cell.CellStyle.Alignment = HorizontalAlignment.LEFT;
cell.SetCellValue(ZConvert.ToString(value));
break;
}
}
rowIndex++;
}
#endregion
#region 将数据写到内存数据流
MemoryStream ms = new MemoryStream();
workbook.Write(ms);
ms.Flush();
ms.Position = ;//指定当前流的位置从0开始 workbook = null;
sheet = null;
row = null;
#endregion
return ms;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 设置excel表头样式
/// </summary>
/// <param name="workbook"></param>
/// <returns></returns>
private static ICellStyle GetHeadStyle(HSSFWorkbook workbook)
{
//表头样式
var headStyle = workbook.CreateCellStyle();
headStyle.Alignment = HorizontalAlignment.LEFT;//居中对齐
//表头单元格背景色
headStyle.FillForegroundColor = HSSFColor.LIGHT_GREEN.index;
headStyle.FillPattern = FillPatternType.SOLID_FOREGROUND;
//表头单元格边框
headStyle.BorderTop = BorderStyle.THIN;
headStyle.TopBorderColor = HSSFColor.BLACK.index;
headStyle.BorderRight = BorderStyle.THIN;
headStyle.RightBorderColor = HSSFColor.BLACK.index;
headStyle.BorderBottom = BorderStyle.THIN;
headStyle.BottomBorderColor = HSSFColor.BLACK.index;
headStyle.BorderLeft = BorderStyle.THIN;
headStyle.LeftBorderColor = HSSFColor.BLACK.index;
//表头字体设置
var font = workbook.CreateFont();
font.FontHeightInPoints = ;//字号
font.Boldweight = ;//加粗
//font.Color = HSSFColor.WHITE.index;//颜色
headStyle.SetFont(font); return headStyle;
}
/// <summary>
/// 设置excel数据行样式
/// </summary>
/// <param name="workbook"></param>
/// <returns></returns>
private static ICellStyle GetDataStyle(HSSFWorkbook workbook)
{
//数据样式
var dataStyle = workbook.CreateCellStyle();
dataStyle.Alignment = HorizontalAlignment.LEFT;//左对齐
//数据单元格的边框
dataStyle.BorderTop = BorderStyle.THIN;
dataStyle.TopBorderColor = HSSFColor.BLACK.index;
dataStyle.BorderRight = BorderStyle.THIN;
dataStyle.RightBorderColor = HSSFColor.BLACK.index;
dataStyle.BorderBottom = BorderStyle.THIN;
dataStyle.BottomBorderColor = HSSFColor.BLACK.index;
dataStyle.BorderLeft = BorderStyle.THIN;
dataStyle.LeftBorderColor = HSSFColor.BLACK.index;
//数据的字体
var datafont = workbook.CreateFont();
datafont.FontHeightInPoints = ;//字号
dataStyle.SetFont(datafont); return dataStyle;
}
DataTable to Excel(使用NPOI、EPPlus将数据表中的数据读取到excel格式内存中)的更多相关文章
- 【Paddy】如何将物理表分割成动态数据表与静态数据表
前言 一般来说,物理表的增.删.改.查都受到数据量的制约,进而影响了性能. 很多情况下,你所负责的业务关键表中,每日变动的数据库与不变动的数据量比较,相差非常大. 这里我们将变动的数据称为动态数据,不 ...
- MySql——创建数据表,查询数据,排序查询数据
参考资料:<Mysql必知必会> 创建数据表 在学习前首先创建数据表和插入数据.如何安装mysql可以看看上个博客https://www.cnblogs.com/lbhym/p/11675 ...
- python连接mysql数据表查询表获取数据导入到txt中
import pymysql'''连接mysql数据表查询表获取数据导入到txt中'''#查询结果写入数据到txtdef get_loan_number(file_txt): connect = py ...
- python openpyxl模块实现excel的读取,新表创建及原数据表追加新数据
当实际工作需要把excel表的数据读取出来,或者把一些统计数据写入excel表中时,一个设计丰富,文档便于寻找的模块就会显得特别的有吸引力,本文对openpyxl模块的一些常见用法做一些记录,方便工作 ...
- 删除数据表和清空数据表的内容(保存表结构)的SHELL脚本
A,删除指定数据库的所有数据表 #!/bin/bash # 删除mysql中所有表 # 示例: # Usage: ./script user password dbnane # Usage: ./sc ...
- Mysql学习(慕课学习笔记4)创建数据表、查看数据表、插入记录
创建数据表 Create table [if not exists] table_name(column_name data_type,…….) UNSIGNED 无符号SIGNED 有符号 查看创建 ...
- SQL学习之Insert的特殊用法(插入检索出的数据,表之间的数据复制)
1.插入检索出的数据 select * from dbo.Customers_1
- mysqldump 导出数据表,和数据
目录 导出数据库表与数据 导出数据表数据 导出多个表数据 只导出数据 只导出创建表的数据 导出数据库表与数据 mysqldump -uroot -p caomall>tmp.sql 导出数据表数 ...
- Oracle数据表之间的数据同步
保证两个数据表结构相同,如不相同只能同步相同字段; 只是思路,具体请根据需求修改. declare cursor csrn_mon is select * from table2; row_mon c ...
随机推荐
- ongl(原始类型和包装类型)
原始类型和包装类型 //首先创建两个实体类 user 和 address user中包含address package cn.jbit.bean; public class User { //用户类 ...
- mac下openresty安装
//openresty安装 http://openresty.org/ brew updatebrew install pcre openssl ./configure --prefix=/usr/l ...
- [LeetCode] Longest Substring with At Most K Distinct Characters 最多有K个不同字符的最长子串
Given a string, find the length of the longest substring T that contains at most k distinct characte ...
- [LeetCode] Linked List Cycle 单链表中的环
Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using ex ...
- 安装Anaconda
安装Anaconda来安装一切 spyder是python科学计算IDE,类似matlab.这是一个基于Qt的软件,如果使用pip install安装,会出现各种bug.pip install spy ...
- EncodingHelper
/// <summary> /// Url解码 /// </summary> /// <param name="str">原始字符串</p ...
- 理解OAuth 2.0
转自:http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html OAuth是一个关于授权(authorization)的开放网络标准,在全世界得到广泛 ...
- SQL基础语法(二)
SQL SELECT 语句 本章讲解 SELECT 和 SELECT * 语句. SQL SELECT 语句 SELECT 语句用于从表中选取数据. 结果被存储在一个结果表中(称为结果集). SQL ...
- CSS:position:fixed使用(转)
position属性规定元素的定位类型,即建立元素布局所用的定位机制.任何元素都可以定位,不过绝对定位或固定定位元素会生成一个块级框,而不论该元素本身是什么类型.相对定位元素会相对于它在正常流中的默认 ...
- 精通Web Analytics 2.0 (8) 第六章:使用定性数据解答”为什么“的谜团
精通Web Analytics 2.0 : 用户中心科学与在线统计艺术 第六章:使用定性数据解答"为什么"的谜团 当我走进一家超市,我不希望员工会认出我或重新为我布置商店. 然而, ...