NPOI的使用Excel模板导出 可插入到指定行
Excel模版建议把需要添加数据行的样式设置好
模版样式
,导出后效果
【2017-11-22 对获取需插入数据的首行样式有时为空报错修改】
/// <summary>
/// 根据模版导出Excel
/// </summary>
/// <param name="templateFile">模版路径(包含后缀) 例:"~/Template/Exceltest.xls"</param>
/// <param name="strFileName">文件名称(不包含后缀) 例:"Excel测试"</param>
/// <param name="source">源DataTable</param>
/// <param name="cellKes">需要导出的对应的列字段 例:string[] cellKes = { "Date","Remarks" };</param>
/// <param name="rowIndex">从第几行开始创建数据行,第一行为0</param>
/// <returns>是否导出成功</returns>
public static string ExportScMeeting(string templateFile, string strFileName, DataTable source, string[] cellKes, int rowIndex)
{
templateFile = HttpContext.Current.Server.MapPath(templateFile);
int cellCount = cellKes.Length;//总列数,第一列为0
IWorkbook workbook = null;
try
{
using (FileStream file = new FileStream(templateFile, FileMode.Open, FileAccess.Read))
{
if (Path.GetExtension(templateFile) == ".xls")
workbook = new HSSFWorkbook(file);
else if (Path.GetExtension(templateFile) == ".xlsx")
workbook = new XSSFWorkbook(file);
}
ISheet sheet = workbook.GetSheetAt();
if (sheet != null && source != null && source.Rows.Count > )
{
IRow row; ICell cell;
//获取需插入数据的首行样式
IRow styleRow = sheet.GetRow(rowIndex);
if (styleRow == null)
{
for (int i = , len = source.Rows.Count; i < len; i++)
{
row = sheet.CreateRow(rowIndex);
//创建列并插入数据
for (int index = ; index < cellCount; index++)
{
row.CreateCell(index)
.SetCellValue(!(source.Rows[i][cellKes[index]] is DBNull) ? source.Rows[i][cellKes[index]].ToString() : string.Empty);
}
rowIndex++;
}
}
else
{
for (int i = , len = source.Rows.Count; i < len; i++)
{
row = sheet.CreateRow(rowIndex);
row.HeightInPoints = styleRow.HeightInPoints;
row.Height = styleRow.Height;
//创建列并插入数据
for (int index = ; index < cellCount; index++)
{
cell = row.CreateCell(index, styleRow.GetCell(index).CellType);
cell.CellStyle = styleRow.GetCell(index).CellStyle;
cell.SetCellValue(!(source.Rows[i][cellKes[index]] is DBNull) ? source.Rows[i][cellKes[index]].ToString() : string.Empty);
}
rowIndex++;
}
}
}
return NPOIExport(strFileName + "." + templateFile.Split('.')[templateFile.Split('.').Length - ], workbook);
}
catch (Exception ex)
{
return ex.Message;
} }
附属方法
public static string NPOIExport(string fileName, IWorkbook workbook)
{
try
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
workbook.Write(ms); HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Cache.SetCacheability(System.Web.HttpCacheability.Private);
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
ms.Close();
ms.Dispose();
return "导出成功";
}
catch (Exception ex)
{
return "导出失败";
}
}
调用方法
/// <summary>
/// 后台调用方法
/// </summary>
/// <returns></returns>
public string Exc()
{
return ExcelUtil.ExportScMeeting("~/Template/MonthlyRepair.xls", "ExcelName", new DataTable(), new string[] { "name1", "name2" }, );
}
//前台js调用 window.open('@Url.Action("Exc")');
注:需要在指定行插入数据的话请使用NPOI自带的方法对Excel进行操作
sheet.ShiftRows(0/*开始行*/, sheet.LastRowNum/*结束行*/, 10/*插入总行数,移动大小(行数)--往下移动*/, true/*是否复制行高*/, false/*是否重置行高*/);
示例方法代码
/// <summary>
/// 根据模版导出Excel
/// </summary>
/// <param name="templateFile">模版路径(包含后缀) 例:"~/Template/Exceltest.xls"</param>
/// <param name="strFileName">文件名称(不包含后缀) 例:"Excel测试"</param>
/// <param name="isCover">是否向下覆盖,不覆盖则在rowIndex行插入数据</param>
/// <param name="source">源DataTable</param>
/// <param name="cellKes">需要导出的对应的列字段 例:string[] cellKes = { "Date","Remarks" };</param>
/// <param name="rowIndex">从第几行开始创建数据行,第一行为0</param>
/// <returns>是否导出成功</returns>
public static string ExportScMeeting(string templateFile, string strFileName, bool isCover, DataTable source, string[] cellKes, int rowIndex)
{
templateFile = HttpContext.Current.Server.MapPath(templateFile);
int cellCount = cellKes.Length;//总列数,第一列为0
IWorkbook workbook = null;
try
{
using (FileStream file = new FileStream(templateFile, FileMode.Open, FileAccess.Read))
{
workbook = new HSSFWorkbook(file);
}
ISheet sheet = workbook.GetSheetAt();
if (sheet != null && source != null && source.Rows.Count > )
{
IRow row;
//是否向下覆盖
if (!isCover) sheet.ShiftRows(rowIndex, sheet.LastRowNum, source.Rows.Count, true, false);
//获取需插入数据的首行样式
IRow styleRow = sheet.GetRow(isCover ? rowIndex : (rowIndex + source.Rows.Count));
for (int i = , len = source.Rows.Count; i < len; i++)
{
row = sheet.CreateRow(rowIndex);
//创建列并插入数据
for (int index = ; index < cellCount; index++)
{
row.CreateCell(index)
.SetCellValue(!(source.Rows[i][cellKes[index]] is DBNull) ? source.Rows[i][cellKes[index]].ToString() : string.Empty);
}
rowIndex++;
}
}
return NPOIExport(strFileName + ".xls", workbook);
}
catch (Exception ex)
{
return ex.Message;
}
}
NPOI的使用Excel模板导出 可插入到指定行的更多相关文章
- NPOI的使用Excel模板导出
private string ExportScMeeting(DataTable source) { string templateFile = Server.MapPath(@"Excel ...
- .Net NPOI 根据excel模板导出excel、直接生成excel
一.根据Excel模板导出excel 1.导入NPOI.dll 2.DAL中添加类ExportExcel.cs using NPOI.SS.UserModel; using System; usin ...
- ASP.NET Core 2.2 : 十六.扒一扒新的Endpoint路由方案 try.dot.net 的正确使用姿势 .Net NPOI 根据excel模板导出excel、直接生成excel .Net NPOI 上传excel文件、提交后台获取excel里的数据
ASP.NET Core 2.2 : 十六.扒一扒新的Endpoint路由方案 ASP.NET Core 从2.2版本开始,采用了一个新的名为Endpoint的路由方案,与原来的方案在使用上差别不 ...
- 基于EPPlus和NPOI实现的Excel导入导出
基于EPPlus和NPOI实现的Excel导入导出 CollapseNav.Net.Tool.Excel(NuGet地址) 太长不看 导入 excel 文件流将会转为 ExcelTestDto 类型的 ...
- java实现excel模板导出
一. 准备工作 1. 点击此下载相关开发工具 2. 将poi-3.8.jxls-core-1.0两个jar包放到工程中,并引用 3. 将excel模板runRecord.xls放到RunRecordB ...
- kettle 使用excel模板导出数据
通过excel进行高速开发报表: 建设思路: 1.首先制订相关的execl模板. 2.通过etl工具(kettle)能够高速的 将数据库中的数据按excel模板导出成新的excel就可以. 当中ket ...
- Magicodes.IE之Excel模板导出教材订购表
说明 本教程主要说明如果使用Magicodes.IE.Excel完成教材订购表的Excel模板导出. 要点 本教程使用Magicodes.IE.Excel来完成Excel模板导出 需要通过创建Dto来 ...
- Excel模板导出之动态导出
说明 目前Magicodes.IE已支持Excel模板导出时使用JObject.Dictionary和ExpandoObject来进行动态导出,具体使用请看本篇教程. 本功能的想法.部分实现初步源于a ...
- C#实现Excel模板导出和从Excel导入数据
午休时间写了一个Demo关于Excel导入导出的简单练习 1.窗体 2.引用office命名空间 添加引用-程序集-扩展-Microsoft.Office.Interop.Excel 3.封装的Exc ...
随机推荐
- [转]Git,SVN的优缺点及适合的范围,开源项目?公司项目?
使用git不久,粗浅理解: 1)适用对象不同.Git适用于参与开源项目的开发者.他们由于水平高,更在乎的是效率而不是易用性.Svn则不同,它适合普通的公司开发团队.使用起来更加容易. 2)使用的场合不 ...
- 【题解搬运】PAT_L1-009 N个数求和
从我原来的博客上搬运.原先blog作废. (伪)水题+1,旨在继续摸清这个blog(囧 题目 就是求N个数字的和.麻烦的是,这些数字是以有理数"分子/分母"的形式给出的,你输出的和 ...
- python基础训练营01
一.基础讲解: 1.1 文件末尾的.py后缀,指出这个文件,是一个python文件,因此,系统将使用python解释器来运行该文件,确定文件中每一个单词的含义. 1.2 python编辑/运行方法: ...
- BZOJ 4029 HEOI2015 定价 数位贪心
题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=4029 题意概述:对于一个数字的荒谬程度定义如下:删除其所有的后缀0,然后得到的数字长度为a ...
- HDU 3697 Selecting courses(贪心+暴力)(2010 Asia Fuzhou Regional Contest)
Description A new Semester is coming and students are troubling for selecting courses. Students ...
- Linux e1000e网卡驱动
目录 识别网卡 命令行参数 附加配置 技术支持 一.识别网卡e1000e驱动支持Intel所有的GbE PCIe网卡,除了82575,82576,基于82580系列的网卡.提示:Intel(R) PR ...
- pta数组作业
7-2 设计思路:本题要求处理数据并输出最大值及其对应的最小下标,首先输入n,然后定义一个长度为n的数组用于存储数据,定义m=a[0],n=0,从a[1]开始与m进行比较,若某项大于m,就把该项的值赋 ...
- B树(B-树)
1.基本概念: M定义为树的高度,也叫阶,就是树的深度: (1).B树又称为多路平衡查找树. (2).根节点至少有两个子节点. (3).除根节点以外的非叶子节点的儿子树为[M/2,M]. (4).每个 ...
- PAT 1065 单身狗
https://pintia.cn/problem-sets/994805260223102976/problems/994805266942377984 “单身狗”是中文对于单身人士的一种爱称.本题 ...
- python3 urllib和requests模块
urllib模块是python自带的,直接调用就好,用法如下: 1 #处理get请求,不传data,则为get请求 2 import urllib 3 from urllib.request impo ...