开发过程中各类报表导入导出防不胜防,网上也是各种解决方法层出不穷,比如Excel,CSV,Word,PDF,HTML等等。。。

  

    网上各种导出插件也是层出不穷,NPOI,微软Microsoft.Office.Interop.Excel,EPPlus等等,其实说起来,微软自带的家伙还是不错的,但是必须要安装office组件,这个不能忍,服务器上安装一个office,呵呵哒!

    

    今天给大家介绍的Excel导入导出用的是NPOI,这个组件还是蛮好用的,而且不依赖office组件。可以根据Excel格式进行自定义。根据平常用到的一些用法进行了封装,旨在更方便的进行文档操作。

    

    我们在Ado.Net里面,DataTable用到的非常多;但是在EF里面,我们更多的是针对List进行操作,毕竟Linq的好处大家都是非常明白,下面通过几个示例分别介绍Excel的导出:

    DataTable导出Excel

 /// <summary>
/// DataTable导出到Excel
/// </summary>
/// <param name="dt"></param>
/// <param name="filename">文件名</param>
/// <param name="sheetname">表名</param>
/// <param name="maxrow">超过行数新建表</param>
/// <param name="isweb">是否web导出,默认是</param>
/// <returns></returns>
public static void DataTableToExcel(string filename, DataTable dt, string sheetname = "", int maxrow = , bool isweb = true)
{
if (dt == null || dt.Rows.Count < )
return;
if (filename.IndexOf(".xls", StringComparison.OrdinalIgnoreCase) < && filename.IndexOf(".xlsx", StringComparison.OrdinalIgnoreCase) < )
filename += ".xls";
IWorkbook workbook = new HSSFWorkbook();
if (sheetname.IsNullOrEmpty())
sheetname = filename;
if (dt.Rows.Count < maxrow)
WriteExcel(dt, , dt.Rows.Count - , workbook, sheetname);
else
{
int page = dt.Rows.Count / maxrow;
for (int i = ; i < page; i++)
{
int start = i * maxrow;
int end = (i * maxrow) + maxrow - ;
WriteExcel(dt, start, end, workbook, sheetname + i);
}
int lastPageItemCount = dt.Rows.Count % maxrow;
WriteExcel(dt, dt.Rows.Count - lastPageItemCount, lastPageItemCount, workbook, sheetname + page);
} using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
if (!isweb)
{
if (!filename.Contains("\\"))
filename = Config.Config.GenerateFilePath("Office") + filename; if (!File.Exists(filename))
{
using (FileStream fs = new FileStream(filename, FileMode.CreateNew))
{
fs.Write(ms.ToArray(), , ms.ToArray().Length);
fs.Close();
}
}
}
else
{
//Web导出
HttpContext curContext = HttpContext.Current;
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = Encoding.UTF8;
curContext.Response.Charset = "";
curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename, Encoding.UTF8));
curContext.Response.BinaryWrite(ms.GetBuffer());
curContext.Response.End();
}
}
}    private static void WriteExcel(DataTable dt, int start, int end, IWorkbook book, string sheetName)
{
ISheet sheet = book.CreateSheet(sheetName);
IRow header = sheet.CreateRow();
for (int i = ; i < dt.Columns.Count; i++)
{
ICell cell = header.CreateCell(i);
string val = dt.Columns[i].Caption ?? dt.Columns[i].ColumnName;
cell.SetCellValue(val);
}
int rowIndex = ;
for (int i = start; i <= end; i++)
{
DataRow dtRow = dt.Rows[i];
IRow excelRow = sheet.CreateRow(rowIndex++);
for (int j = ; j < dtRow.ItemArray.Length; j++)
excelRow.CreateCell(j).SetCellValue(dtRow[j].ToString().Trim());
}
}   调用方式:
public void Test()
{
  Excel.DataTableToExcel("dt7.xls",dt,"人员名录");
}


  List导出Excel:

/// <summary>
/// List导出Excel
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="filename">文件名称和路径</param>
/// <param name="sheetname">表名称</param>
/// <param name="data">数据</param>
/// <param name="title">表头</param>
/// <param name="isweb">是否web导出,默认是</param>
public static void ListToExcel<T>(string filename, string sheetname, List<T> data, List<string> title = null, bool isweb = true) where T : new()
{
if (data.Count < )
return;
if (filename.IndexOf(".xls", StringComparison.OrdinalIgnoreCase) < && filename.IndexOf(".xlsx", StringComparison.OrdinalIgnoreCase) < )
filename += ".xls";
var wookbook = new HSSFWorkbook();
var sheet = wookbook.CreateSheet(sheetname);
var entity = new T();
var propertys = entity.GetType().GetProperties(); if (title == null || title.Count < )
{
title = new List<string>();
foreach (PropertyInfo item in propertys)
{
if (!Ignore.IgnoreField(item.Name))
continue; title.Add(item.Name);
}
} var rowtitle = sheet.CreateRow(); for (var i = ; i < title.Count; i++)
rowtitle.CreateCell(i).SetCellValue(title[i]); for (var i = ; i < data.Count; i++)
{
var row = sheet.CreateRow(i + ); //因为表头名称占了一行,所以加1
for (var j = ; j < propertys.Length; j++)
{
if (!Ignore.IgnoreField(propertys[j].Name))
continue; var obj = propertys[j].GetValue(data[i], null);
row.CreateCell(j).SetCellValue(obj.ToString().Trim());
}
}
if (!isweb)
{
if (!filename.Contains("\\"))
filename = Config.Config.GenerateFilePath("Office") + filename; if (!File.Exists(filename))
{
using (var fs = new FileStream(filename, FileMode.CreateNew))
{
wookbook.Write(fs);
}
}
}
else
{
using (MemoryStream ms = new MemoryStream())
{
wookbook.Write(ms);
//Web导出
HttpContext curContext = HttpContext.Current;
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = Encoding.UTF8;
curContext.Response.Charset = "";
curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename, Encoding.UTF8));
curContext.Response.BinaryWrite(ms.GetBuffer());
curContext.Response.End();
}
}
}   
  调用方法:

  
  public void Test()
  {
    Excel.ListToExcel(path,"",list,newList<string>(){"编号","名字","时间"});
  }


OK,各位看官,这一期的文章Excel导出写到这里喏,感谢大家的支持,您的支持是我的动力!

下一期给大家带来的是常用的Excel导入,敬请期待!!!

 

Asp.Net 常用工具类之Office—Excel导出(4)的更多相关文章

  1. Asp.Net 常用工具类之Office—Excel导入(5)

    之前在做一个项目的时候,客户方面只提供了一份简单的Excel文件,且要跟现有数据进行对接. 当时想到的是如果数据量不大,可以Excel一条一条加进去,无奈数据有几十兆!!! 换了一种思维,进行了导入: ...

  2. Asp.Net 常用工具类---Config操作(7)

    近期工作比较忙,忙到忘记写博客(自己的借口,主要加班下班后不想动). 月初的时候,打算每两天写一篇博文,分享自己的一些心得和开发体验,无奈现在只写到第六篇,然而时间已经是20号,岁月不饶人! 总想写点 ...

  3. Asp.Net 常用工具类之Office-文档操作(6)

    文档一直是老大难问题,君不知,代码用时方恨少!有一套成熟的文件帮助类能很大程度上减少寻找各种资料的时间. 记得以前做一个业务,需要导出协议,一份可编辑,一份不可编辑.那么Word和PDF是最好的选择, ...

  4. Asp.Net 常用工具类之加密——非对称加密RSA算法

    踏入程序员这个行业也有几年了,几年中有收获(技术加强),有付出(时间和亚健康状态).当然喏,并不后悔,代码路还长!!! On The Way,永不止步!!! 开发过程中也积累了一些自己的经验.代码块和 ...

  5. Asp.Net 常用工具类之加密——对称加密DES算法(2)

    又到周末,下午博客园看了两篇文章,关于老跳和老赵的程序员生涯,不禁感叹漫漫程序路,何去何从兮! 转眼毕业的第三个年头,去过苏州,跑过上海,从一开始的凌云壮志,去年背起行囊默默回到了长沙准备买房,也想有 ...

  6. C#常用工具类——Excel操作类

    /// 常用工具类——Excel操作类 /// <para> ------------------------------------------------</para> / ...

  7. C#常用工具类——Excel操作类(ZT)

    本文转载于: http://www.cnblogs.com/zfanlong1314/p/3916047.html /// 常用工具类——Excel操作类 /// <para> ----- ...

  8. [C#] 常用工具类——文件操作类

    /// <para> FilesUpload:工具方法:ASP.NET上传文件的方法</para> /// <para> FileExists:返回文件是否存在&l ...

  9. PHP常用工具类

    <?php namespace isslib\Util; use think\Config; /** * 常用工具类 * User: xaxiong * Date: 2016/12/19 * T ...

随机推荐

  1. Delphi中解析Xml的控件-SimDesign NativeXml

    Delphi中解析Xml的控件-SimDesign NativeXml 正在学习,感觉应用很方便.无源代码的版本还是免费的. SimDesign.NativeXml是一个delphi和bcb的XML控 ...

  2. --@angularJS--指令与指令之间的交互demo

    1.index.html: <!DOCTYPE HTML><html ng-app="app"><head>    <title>c ...

  3. HTML模块化:使用HTML5 Boilerplate模板

    HTML5 Boilerplate 是一个由 Paul Irish(Google Chrome 开发人员.jQuery 项目成员.Modernizr 作者.yayQuery 播客主持人)主导的“前端开 ...

  4. Windows Server 2012的配置与部署

    一. 背景 这里以阿里云Windows Server 2012系统的服务器为主,介绍服务器的配置以及.Net程序的发布顺序,在后续的项目管理文章中,会介绍<运维手册>的写法. 二. 步骤 ...

  5. Linux文件权限与目录配置

    一.linux文件属性 用户组概念:假如主机有两个团体,第一个团体名为projecta,里面有class1,class2,class3:第二个团体名为projecb,里面有class4,class5, ...

  6. 如何使用Ninja快速编译LLVM和Clang

    在使用Make工具编译LLVM是非常耗时的.往往需要三四个小时.但是使用goolge开源的ninja编译LLVM只需要10到20分钟. 本文以llvm3.3为例,演示在linux上编译和安装过程. 第 ...

  7. Java泛型中的通配符的使用

    package com.srie.testjava; import java.util.ArrayList; import java.util.List; public class TestClass ...

  8. 微信小程序t填坑之旅一(接入)

    一.小程序简介 小程序是什么? 首先"程序"这两个字我们不陌生.看看你手机上的各个软件,那就是程序.平时的程序是直接跑在我们原生的操作系统上面的.小程序是间接跑在原生系统上的.因为 ...

  9. Spring IO Platform简介及示例

    什么是Spring IO Platform Spring IO Platform,简单的可以认为是一个依赖维护平台,该平台将相关依赖汇聚到一起,针对每个依赖,都提供了一个版本号: 这些版本对应的依赖都 ...

  10. 一步一步学Java IO

    1.基本概念 1.1.InputStream 最基本的字节输入流,抽象类,定义了读取原始字节的所有基本方法1.1.1.public abstract int read() throws IOExcep ...