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模板导出 可插入到指定行的更多相关文章

  1. NPOI的使用Excel模板导出

    private string ExportScMeeting(DataTable source) { string templateFile = Server.MapPath(@"Excel ...

  2. .Net NPOI 根据excel模板导出excel、直接生成excel

    一.根据Excel模板导出excel 1.导入NPOI.dll  2.DAL中添加类ExportExcel.cs using NPOI.SS.UserModel; using System; usin ...

  3. 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的路由方案,与原来的方案在使用上差别不 ...

  4. 基于EPPlus和NPOI实现的Excel导入导出

    基于EPPlus和NPOI实现的Excel导入导出 CollapseNav.Net.Tool.Excel(NuGet地址) 太长不看 导入 excel 文件流将会转为 ExcelTestDto 类型的 ...

  5. java实现excel模板导出

    一. 准备工作 1. 点击此下载相关开发工具 2. 将poi-3.8.jxls-core-1.0两个jar包放到工程中,并引用 3. 将excel模板runRecord.xls放到RunRecordB ...

  6. kettle 使用excel模板导出数据

    通过excel进行高速开发报表: 建设思路: 1.首先制订相关的execl模板. 2.通过etl工具(kettle)能够高速的 将数据库中的数据按excel模板导出成新的excel就可以. 当中ket ...

  7. Magicodes.IE之Excel模板导出教材订购表

    说明 本教程主要说明如果使用Magicodes.IE.Excel完成教材订购表的Excel模板导出. 要点 本教程使用Magicodes.IE.Excel来完成Excel模板导出 需要通过创建Dto来 ...

  8. Excel模板导出之动态导出

    说明 目前Magicodes.IE已支持Excel模板导出时使用JObject.Dictionary和ExpandoObject来进行动态导出,具体使用请看本篇教程. 本功能的想法.部分实现初步源于a ...

  9. C#实现Excel模板导出和从Excel导入数据

    午休时间写了一个Demo关于Excel导入导出的简单练习 1.窗体 2.引用office命名空间 添加引用-程序集-扩展-Microsoft.Office.Interop.Excel 3.封装的Exc ...

随机推荐

  1. Android AppWidget偶尔无响应原因及解决办法

    Android AppWidget偶尔会出现无响应问题,如按钮点击失效,数据不更新等等. 测试后发现,一般出现在手机用清理工具(或系统自己)清理后发生,或手机重启后发生. 目前经过测试,找到的办法是把 ...

  2. 「暑期训练」「Brute Force」 Far Relative’s Problem (CFR343D2B)

    题意 之后补 分析 我哭了,强行增加自己的思考复杂度...明明一道尬写的题- -(往区间贪心方向想了 其实完全没必要,注意到只有366天,直接穷举判断即可. 代码 #include <bits/ ...

  3. python------- IO 模型

                                                    IO模型介绍                                               ...

  4. 使用CodeBlocks编译64位程序(用的编译器仅仅是windows sdk的)

    需求: -CodeBlocks使用nightly版本: -Windows SDK(我使用的是6.0A,即微软针对vista的,因为这个比较小,你也可以选择其他版本但是要有64位编译器.他也适用于xps ...

  5. Visual Studio Code 配置Go 开发环境最简单的方法!!!

    由于大家都知道的原因,在国内如果想访问go等各种资源,都会遇到某种不可预知的神奇问题.导致在VS Code中安装 go 各种插件都会失败. 于是乎,网上就出现了各种各样的解决方案:什么手动git cl ...

  6. 简单的素数问题(C++)

    [问题描述] 已知三个素数的和为 n ,正整数 n 由键盘输入,计算并输出这三个素数乘积的最大值. [代码展示] # include<iostream>using namespace st ...

  7. redis字符串基本操作

    redis之字符串类型: 字符串类型是redis中最基本的数据类型,同时它也是memcached中仅有的数据类型.redis字符串类型的键能存储任何形式的字符串,包括二进制数据,例如,存储json化的 ...

  8. Week3 Teamework from Z.XML-团队分工及贡献分分配办法

    引言:团队项目即将开展,本文将就团队分工,以及分数分配办法进行阐述 一.团队分工 本周我们团队进行了初步的分工,结果如下: PM: 李孟 Dev:毛宇 薛亚杰 肖俊鹏 罗凡 Test:周敏轩 马辰 李 ...

  9. xampp开户,apache打开出现端口被占用提示

    刚装上去的时候,可以打开xampp,但是重启的时候出现以后以下问题 13:49:02  [Apache]     Error: Apache shutdown unexpectedly.13:49:0 ...

  10. phpStoram破解方法