前言

分别介绍两种导出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. ICSharpCode.SharpZipLib工具压缩与解压缩zip文件

    using System; using System.Collections.Generic; using System.IO; using System.Text; using ICSharpCod ...

  2. sql server服务看不到,显示为远程过程调用在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误10061

    需要启动sql server服务 启动就可以完成登录了

  3. AutoFac文档6(转载)

    目录 开始 Registering components 控制作用域和生命周期 用模块结构化Autofac xml配置 与.net集成 深入理解Autofac 指导 关于 词汇表 实例生命周期 实例生 ...

  4. Hystrix的用法demo

    1.引入依赖 <dependency> <groupId>org.springframework.cloud</groupId> <artifactId> ...

  5. 区别:Use MFC In A Shared DLL 和 Use MFC In A Static Library

    摘自:Programming Windows with MFC, 2nd Edition Choosing Use MFC In A Shared DLL minimizes your applica ...

  6. jquery头文件的引入

    <script type="text/javascript" src="/library/js/jquery/jquery-1.9.1.min.js"&g ...

  7. Ubuntu 下添加OpenERP command 快捷启动方式

    编辑home目录下的.bashrc文件 alias xjerp="~/odoo/xj/openerp-server -r openerp --addons-path='~/odoo/xj/o ...

  8. UCOS2系统内核讲述_总体描述

    Ⅰ.写在前面 学习本文之前可以参考我前面基于STM32硬件平台移植UCOS2的几篇文章,我将其汇总在一起: UCOS2_STM32F1移植详细过程(汇总文章) 要想学习,或使用系统配套的资源(如:信号 ...

  9. 科技巨头们以 "A" 取名的时尚潮流

    科技巨头们以 "A" 取名的时尚潮流 from 公众号  WebHub  世界上有许多巨头公司喜欢以字母 a 打头作公司起名.改名,这主要是因为电话薄是以字母排序的(外国人习惯家里 ...

  10. Android不同版本下Notification创建方法

    项目环境 Project Build Target:Android 6.0 问题: 使用 new Notification(int icon, CharSequence tickerText, lon ...