前言

分别介绍两种导出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. js获取当前域名的方法

    一.获取当前域名 1.方法一 var domain = document.domain; 2.方法二 var domain = window.location.host; 但是获取到的domain在线 ...

  2. H5 input 聚焦 置顶

    myFocus (e) { this.active = true function getElementTop(element){ try { var actualTop = element.offs ...

  3. 使用 log4j 2记录日志

    log4j2使用方法还是很简单的 1 需要使用的jar包有两个, 1)log4j-api-2.8.2.jar 2)log4j-core-2.8.2.jar 2 产生Logger 对象非常的简单,使用  ...

  4. Js/jQuery实时监听输入框值变化

    前言 在做web开发时候很多时候都需要即时监听输入框值的变化,以便作出即时动作去引导浏览者增强网站的用户体验感.而采用onchange时间又往往是在输入框失去焦点(onblur)时候触发,有时候并不能 ...

  5. centos5.5 快速安装mysql

    安装MySQL. [root@sample ~]# yum -y install mysql-server ← 安装MySQL[root@sample ~]# yum -y install php-m ...

  6. 【原创】k8s源代码分析-----kubelet(1)主要流程

    本人空间链接http://user.qzone.qq.com/29185807/blog/1460015727 源代码为k8s v1.1.1稳定版本号 kubelet代码比較复杂.主要是由于其担负的任 ...

  7. path方法总结

    $.mobile.path.get(url);//获取URL地址的目录部分,就是除了a.html之外的那部分 jQuery.mobile.path.getDocumentBase(bool) //获取 ...

  8. 导出word功能,用html代码在word中插入分页符

    <span lang=EN-US style="font-size:10.5pt;mso-bidi-font-size:12.0pt;font-family:" mce_st ...

  9. linux命令之fuser

    Usage: fuser [ -a | -s | -c ] [ -n SPACE ] [ -SIGNAL ] [ -kimuv ] NAME... [ - ] [ -n SPACE ] [ -SIGN ...

  10. SAP ECC6安装系列二:安装前的准备工作

    原作者博客 http://www.cnblogs.com/Michael_z/ ======================================== 安装 Java  1,安装 Java, ...