前言

分别介绍两种导出Exce表格的方法和读取Excel表格数据方法。

1、在MVC下的表格导出。

2、基于NPOI的表格导出。

3、读取Excel表格数据。

第一种方法:在MVC下的表格导出。

首先,创建一个数据model,代码如下:

 public class ListModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Password { get; set; }
}

一个表格model,代码如下:

  public class ExcelModel
{
[Display(Name = "ID")]
public int Id { get; set; }
[Display(Name = "第一列")]
public string Head { get; set; }
[Display(Name = "第二列")]
public string Center { get; set; }
}

其次,创建一个操作表格的类,代码如下:

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using System.Web.UI.WebControls; namespace Excel1.Helper
{
public class EecelHelper<T>:ActionResult
{
private string _fileName;
private List<T> _rows;
private List<string> _headers;
private TableStyle _tableStyle;
private TableItemStyle _headerSytle;
private TableItemStyle _itemStyle;
public string FileName
{
get { return _fileName; }
}
public List<T>Rows
{
get { return _rows; }
}
public EecelHelper(List<T> rows,string fileName )
:this(rows,fileName,null,null,null,null)
{ }
public EecelHelper(List<T>rows,string fileName,List<string>headers )
:this(rows,fileName,headers,null,null,null)
{ }
public EecelHelper(List<T> rows, string fileName, List<string> headers,TableStyle tableStyle,TableItemStyle headerSytle,TableItemStyle itemStyle) {
_rows = rows;
_fileName = string.IsNullOrEmpty(fileName) ? DateTime.Now.ToString("yyyyMMddHHmmss") : fileName;
_headers = headers;
_tableStyle = tableStyle;
_headerSytle = headerSytle;
_itemStyle = itemStyle;
if(_tableStyle==null)
{
_tableStyle = new TableStyle();
_tableStyle.BorderStyle = BorderStyle.Solid;
_tableStyle.BorderColor = Color.Black;
_tableStyle.BorderWidth = Unit.Parse("2px");
}
if(_headerSytle == null)
{
_headerSytle = new TableItemStyle();
_headerSytle.BackColor = Color.LightGray;
}
} public override void ExecuteResult(ControllerContext context)
{
StringWriter sw = new StringWriter();
HtmlTextWriter tw = new HtmlTextWriter(sw); if(_tableStyle !=null)
{
_tableStyle.AddAttributesToRender(tw);
}
tw.RenderBeginTag(HtmlTextWriterTag.Table);
var properties = TypeDescriptor.GetProperties(typeof (T)); if(_headers == null)
{
_headers = new List<string>();
for(int i=;i<properties.Count;i++)
{
var attr = typeof (T).GetProperty(properties[i].Name).GetCustomAttributes(
typeof (DisplayAttribute), true);
_headers.Add(attr.Length>?((DisplayAttribute)attr[]).Name:properties[i].Name);
}
}
tw.RenderBeginTag(HtmlTextWriterTag.Thead);
foreach (string header in _headers)
{
if(_headerSytle != null)
_headerSytle.AddAttributesToRender(tw);
tw.RenderBeginTag(HtmlTextWriterTag.Th);
tw.Write(header);
tw.RenderEndTag();
} tw.RenderBeginTag(HtmlTextWriterTag.Tbody);
foreach (var row in _rows)
{
tw.RenderBeginTag(HtmlTextWriterTag.Tr);
for(int i=;i<properties.Count;i++)
{
var strValue = properties[i].GetValue(row) == null
? string.Empty
: properties[i].GetValue(row).ToString();
strValue = ReplaceSpecialCharacters(strValue);
if(_itemStyle != null)
_itemStyle.AddAttributesToRender(tw);
tw.RenderBeginTag(HtmlTextWriterTag.Td);
tw.Write(HttpUtility.HtmlEncode(strValue));
tw.RenderEndTag();
}
tw.RenderEndTag();
}
tw.RenderEndTag();
tw.RenderEndTag();
WriteFile(_fileName, "application/ms-excel", sw.ToString());
} private static string ReplaceSpecialCharacters(string value)
{
value = value.Replace("' ", "'");
value = value.Replace("“", "\"");
value = value.Replace("”", "\"");
value = value.Replace("—", "-");
value = value.Replace("...", "");
return value;
}
private static void WriteFile(string fileName,string contentType,string content)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.AddHeader("content-disposition","attachment;filename="+fileName+".xls");
context.Response.ContentEncoding = Encoding.Default;
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = contentType;
context.Response.Write(content);
context.Response.End();
}
}
}

最后,新建一个方法,这个方法是用来,把数据model转换成表格model的,代码如下:

 public class Mappers
{
public static ExcelModel ExcelModel(ListModel model)
{
return new ExcelModel
{
Id = model.Id,
Head = model.Name,
Center = model.Password,
};
}
}

在控制器下,就可以调用上面创建的操作表格类进行处理了,代码如下:

 public ActionResult Down()
{
List<ListModel> list = new List<ListModel>();
ListModel model = new ListModel();
model.Id = ;
model.Name = "小明";
model.Password = "";
list.Add(model);
var excelList = list.Select(Mappers.ExcelModel).ToList();
return new EecelHelper<ExcelModel>(excelList.ToList(), "我的Excel");
}

第二种方法:基于NPOI的表格导出。

首先下载NPOI.dll http://files.cnblogs.com/zl879211310/bils.rar

其次,把NPOI.dll 放到项目中,创建一个表格操作类,代码如下:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NPOI.HSSF.UserModel;
using System.IO;
using System.Text;
using System.Windows.Forms; namespace Ajax
{
/// <summary>
/// 0.引用bils文件夹的dll
/// 1.新建一个model,里面的字段就是要导出的字段
/// 2.输入List<T>数据,FilePath=@"E:\"
/// 3.每行根据model的字段添加
/// </summary>
public class WorkBook
{
public void BuildWorkBook(List<Student> models,string FilePath) //修改
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.CreateSheet("第一页");
HSSFRow rowHead = sheet.CreateRow();
rowHead.CreateCell().SetCellValue("姓名"); //修改
rowHead.CreateCell().SetCellValue("年龄"); for (int rowIndex = ; rowIndex < models.Count(); rowIndex++)
{
HSSFRow row = sheet.CreateRow(rowIndex + );
row.CreateCell().SetCellValue(models[rowIndex].Name); // 修改
row.CreateCell().SetCellValue(models[rowIndex].Age);
} using (FileStream fs = new FileStream(FilePath + DateTime.Now.ToString("yyyy-MM-dd") + ".xls", FileMode.Create))
{
workbook.Write(fs);
}
}
}
}

最后,调用就可以了,代码如下:

  List<Student> model=new List<Student> (){
new Student {Name="小张",Age=},
new Student {Name="小张1",Age=},
new Student {Name="小张2",Age=},
new Student {Name="小张3",Age=},
new Student {Name="小张4",Age=}
};
WorkBook work = new WorkBook(); string path = @"E:\";
try
{
work.BuildWorkBook(model, path);
Response.Write("<script>alert('导出成功');</script>");
}
catch (Exception)
{
Response.Write("<script>alert('导出失败');</script>");
}

读取Excel表格数据

1、读取excel表格需要的方法,代码如下:

  //获得excel表的地址
private string GetPath(string path)
{
var separetor = Path.DirectorySeparatorChar;
return string.Format(path, separetor);
}
//excel表的版本
private const string ExcelDefaultVersion = "12.0";
//连接字符串
private const string ConnectionStringTemplate =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel {1};HDR=YES;IMEX=1'";//兼容office2003、office2007; private static string GetConnectionString(string excelPath,string excelVersion)
{
return string.Format(CultureInfo.InvariantCulture, ConnectionStringTemplate, excelPath, excelVersion);
} //查询
private static DataSet QueryBySheetName(OleDbConnection conn, string sheetName)
{
var query = string.Format("select * from [{0}]", sheetName);
var adp = new OleDbDataAdapter(query, conn);
var dt = new DataSet();
adp.Fill(dt,"book");//填充到DataSet的 表格名为book的table里。表格名随便取
return dt;
} //创建连接字符串
private static OleDbConnection CreateConnection(string excelPath, string excelVersion = ExcelDefaultVersion)
{
return new OleDbConnection(GetConnectionString(excelPath,excelVersion));
} //查询工作表
public static DataSet Query(string excelPath, string sheetName)
{
using (var conn = CreateConnection(excelPath))
{
var dt = QueryBySheetName(conn, sheetName);
return dt;
}
}

2、调用,代码如下:

  public ActionResult Index()
{
var path = Server.MapPath(GetPath("{0}Content{0}Hero.xlsx"));//获得excel表格地址
DataSet table = Query(path, "Sheet1$");// "Sheet1$"这是读取excel表的哪个工作表,记得加上$
var tables = table.Tables["book"]; for (int i = ; i <= tables.Rows.Count; i++)
{
if (tables.Rows[i][].ToString() != null)
{
if (tables.Rows[i][].ToString() == "")
{
Response.Write(tables.Rows[i][]);
break;
}
}
}
return View();
}

结束

两个小例子,只是简单的实现,为的是用过记录下来。

Excel表导出的更多相关文章

  1. yii2 中excel表导出

    首先下载phpexcel 在引入类文件(在web中index.php入口文件或者控制器中引入) require_once dirname(dirname(__FILE__)).'/excel/PHPE ...

  2. jfinal excel表导出

    在自己的WEB项目中要用到导出Excel,所以结合网络上的资源写了一个自己的export 工具类. 说明: JFinal 环境 WEB项目 JAVA后台生成非JS插件 好了,直接撸代码 1.设置文件保 ...

  3. thinkphp导入导出excel表单数据

    在PHP项目经常要导入导出Excel表单. 先去下载PHPExcel类库文件,放到相应位置. 我在thinkphp框架中的位置为ThinkPHP/Library/Org/Util/ 导入 在页面上传e ...

  4. ASPNET 导出EXCEL表

    其实网上有很多关于Excel的例子,但是不是很好,他们的代码没有很全,读的起来还很晦涩.经过这几天的摸索,终于可以完成我想要导出报表Excel的效果了.下面是我的效果图. 一.前台的页面图 GridV ...

  5. ASP.NET 导出gridview中的数据到Excel表中,并对指定单元格换行操作

    1. 使用NPOI读取及生成excel表. (1)导出Click事件: 获取DataTable; 给文件加文件名: string xlsxName = "xxx_" + DateT ...

  6. 将数据导出成excel表

    /// <summary> /// 生成excel表 /// </summary> /// <param name="dt">数据表</p ...

  7. 数据库多张表导出到excel

    数据库多张表导出到excel public static void export() throws Exception{ //声明需要导出的数据库 String dbName = "hdcl ...

  8. 【ITOO 1】将List数据导出Excel表

    需求描述:在课表导入的时候,首先给用户提供模板(excel),然后将用户填写好的数据读取到list集合中.再进行判空处赋值处理,以及去重处理.这篇博客,主要介绍读取excel表和导出excel表的方法 ...

  9. ASP.NET导出excel表方法汇总

    asp.net里导出excel表方法汇总  1.由dataset生成 public void CreateExcel(DataSet ds,string typeid,string FileName) ...

随机推荐

  1. Python3 casefold() 方法

    描述 Python casefold() 方法是Python3.3版本之后引入的,其效果和 lower() 方法非常相似,都可以转换字符串中所有大写字符为小写. 两者的区别是:lower() 方法只对 ...

  2. 【转载】Linux 系统时间查看 及 时区修改(自动同步时间)

    1:使用date命令查看时区 [root@db-server ~]# date -R   Sun, 11 Jan 2015 07:10:28 -0800   [root@db-server ~]#   ...

  3. (Spring Boot框架)快速入门

    Spring Boot 系列文章推荐 Spring Boot 入门 Spring Boot 属性配置和使用 Spring Boot 集成MyBatis Spring Boot 静态资源处理 今天介绍一 ...

  4. mysql多实例安装详解

    首先说明一个场景:我的电脑是ubuntu系统,之前apt-get自动安装过mysql.这也是出现错误最多的原因之一. 安装过程,其中充斥着各种错误: 6.mkdir mysql 7.groupadd  ...

  5. 【C语言】19-static和extern关键字1-对函数的作用

    一.extern与函数 在前面我提到过一句话:如果一个程序中有多个源文件(.c),编译成功会生成对应的多个目标文件(.obj),这些目标文件还不能单独运行,因为这些目标文件之间可能会有关联,比如a.o ...

  6. MySQL 使用 SSL 连接(附 Docker 例子)

    查看是否支持 SSL 首先在 MySQL 上执行如下命令, 查询是否 MySQL 支持 SSL: mysql> SHOW VARIABLES LIKE 'have_ssl'; +-------- ...

  7. vs2015开发so动态库linux

    #include <stdio.h> #include <dlfcn.h> typedef int(*fn_max)(int a, int b); int main() { p ...

  8. 16V554 的测试代码

    //------------------------------------------------------------------------ #include   "AT16C554 ...

  9. elasticsearch -- 问题纪录

    报错1: [1]: max file descriptors [65535] for elasticsearch process is too low, increase to at least [6 ...

  10. CSS浮动与清除浮动(overflow)例子

    在css中浮动与清除浮动功能是我们开发中常用到的一个功能了,下面小编来为各位分析关于CSS浮动与清除浮动(overflow)例子吧. float脱离文本流,可是为什么文字却会有环绕的效果,这点实在是神 ...