控件bin文件下载地址:https://download.csdn.net/download/u012949335/10610726
@{
ViewBag.Title = "dcxx";
}
<script type="text/javascript" language="javascript"> function excelport()
{
var checktag=$("#ischecked:checked");
var form=$("<form action=\"dcxx\" method=\"post\"></form>");
$(document.body).append(form);
form.submit();
}
</script>
<button type="button" class="but-primary" onclick="excelport()"> 导出数据</button> //调用方法
public ActionResult dcxx()
{ DataTable dt = dal.getlist(" 1=1 ");
NpoiWorkbook book = new NpoiWorkbook();
book.CreateSheet(dt, "xxx信息");
Stream excelstream = book.GetMemoryStream();
return File(excelstream, "application/octet-stream", "xx信息.xls");
} using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using System.IO;
using System.Data;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
namespace YidiTutor.Common.NOPI
{
/// <summary>
/// 工作薄
/// </summary>
public class NpoiWorkbook
{
public HSSFWorkbook workbook;
public XSSFWorkbook workbook2007;
public bool isExcel2007 = false;//生成excel2007
/// <summary>
/// 表头格式
/// </summary>
private ICellStyle HeadStyle
{
get
{
if (!isExcel2007)
{
HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
headStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
HSSFFont font = (HSSFFont)workbook.CreateFont();
font.FontHeightInPoints = ;
font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
font.FontName = "宋体";
headStyle.SetFont(font);
return headStyle;
}
else
{
XSSFCellStyle headStyle = (XSSFCellStyle)workbook2007.CreateCellStyle();
headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
headStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
XSSFFont font = (XSSFFont)workbook2007.CreateFont();
font.FontHeightInPoints = ;
font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
font.FontName = "宋体";
headStyle.SetFont(font);
return headStyle;
}
}
}
private ICellStyle HeadStyle_red
{
get
{
ICellStyle Iheadstyle = null;
if (!isExcel2007)
{
HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
headStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
HSSFFont font = (HSSFFont)workbook.CreateFont();
font.FontHeightInPoints = ;
font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
font.FontName = "宋体";
font.Color = NPOI.HSSF.Util.HSSFColor.Red.Index;
headStyle.SetFont(font);
Iheadstyle = headStyle;
}
else
{
XSSFCellStyle headStyle = (XSSFCellStyle)workbook2007.CreateCellStyle();
headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
headStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
XSSFFont font = (XSSFFont)workbook2007.CreateFont();
font.FontHeightInPoints = ;
font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
font.FontName = "宋体";
font.Color = NPOI.HSSF.Util.HSSFColor.Red.Index;
headStyle.SetFont(font);
Iheadstyle = headStyle;
}
return Iheadstyle;
}
}
/// <summary>
/// 时间格式
/// </summary>
private ICellStyle DateStyle
{
get
{
ICellStyle datestyle = null;
if (!isExcel2007)
{
HSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle();
HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat();
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
datestyle = dateStyle;
}
else
{
XSSFCellStyle dateStyle = (XSSFCellStyle)workbook2007.CreateCellStyle();
XSSFDataFormat format = (XSSFDataFormat)workbook2007.CreateDataFormat();
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
datestyle = dateStyle;
}
return datestyle;
}
} private ICellStyle ContentStyle
{
get
{
ICellStyle contentstyle = null;
if (!isExcel2007)
{
HSSFCellStyle contentStyle = (HSSFCellStyle)workbook.CreateCellStyle();
contentStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
contentStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
HSSFFont font = (HSSFFont)workbook.CreateFont();
font.FontHeightInPoints = ;
font.FontName = "宋体";
contentStyle.SetFont(font);
contentstyle = contentStyle;
}
else
{
XSSFCellStyle contentStyle = (XSSFCellStyle)workbook2007.CreateCellStyle();
contentStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
contentStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
XSSFFont font = (XSSFFont)workbook2007.CreateFont();
font.FontHeightInPoints = ;
font.FontName = "宋体";
contentStyle.SetFont(font);
contentstyle = contentStyle;
}
return contentstyle;
}
} private ICellStyle ContentStyle_red
{
get
{
ICellStyle contentStyle_red = null;
if (!isExcel2007)
{
HSSFCellStyle contentStyle = (HSSFCellStyle)workbook.CreateCellStyle();
contentStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
contentStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
HSSFFont font = (HSSFFont)workbook.CreateFont();
font.FontHeightInPoints = ;
font.FontName = "宋体";
font.Color = NPOI.HSSF.Util.HSSFColor.Red.Index;
contentStyle.SetFont(font);
contentStyle_red = contentStyle;
}
else
{
XSSFCellStyle contentStyle = (XSSFCellStyle)workbook2007.CreateCellStyle();
contentStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
contentStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
XSSFFont font = (XSSFFont)workbook2007.CreateFont();
font.FontHeightInPoints = ;
font.FontName = "宋体";
font.Color = NPOI.HSSF.Util.HSSFColor.Red.Index;
contentStyle.SetFont(font);
contentStyle_red = contentStyle;
}
return contentStyle_red;
}
}
/// <summary>
/// 实例一个工作薄
/// </summary>
public NpoiWorkbook()
{
workbook2007 = new XSSFWorkbook();
workbook = new HSSFWorkbook();
#region 右击文件 属性信息
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "SiBu";
workbook.DocumentSummaryInformation = dsi; SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.CreateDateTime = System.DateTime.Now;
workbook.SummaryInformation = si;
#endregion
} /// <summary>
/// 导出excel初始化
/// </summary>
/// <param name="isexcel2007"></param>
public NpoiWorkbook(bool isexcel2007)
: this()
{
isExcel2007 = isexcel2007;
}
/// <summary>
/// 读取excel初始化,加载Excel文件
/// </summary>
/// <param name="filePath">文件路径</param>
public NpoiWorkbook(string filePath)
{
string filetype = Path.GetExtension(filePath).ToLower();
try
{
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
if (".xls".Equals(filetype))
{
isExcel2007 = false;
}
else
{
isExcel2007 = true;
}
if (filetype.Equals(".xls"))
{
workbook = new HSSFWorkbook(file);
isExcel2007 = false;
}
else
{
workbook2007 = new XSSFWorkbook(file);
isExcel2007 = true;
}
}
}
catch (Exception ex)
{ }
}
/// <summary>
/// 读取excel初始化,加载Excel文件流
/// </summary>
/// <param name="excelstream">excel文件流,使用场景:excel上传导入时候直接获取的文件流</param>
/// <param name="filename">带后缀名的文件名(格式如xx.xls或D:\excel\xx.xls)</param>
public NpoiWorkbook(Stream excelstream, string filename)
{
string filetype = Path.GetExtension(filename).ToLower();
if (".xls".Equals(filetype))
{
workbook = new HSSFWorkbook(excelstream);
isExcel2007 = false;
}
else
{
workbook2007 = new XSSFWorkbook(excelstream);
isExcel2007 = true;
} }
/// <summary>
/// 获取Sheet页的数据
/// </summary>
/// <param name="sheetIndex">Sheet页Index,从0开始</param>
/// <returns>DataTable</returns>
public DataTable GetDataTable(int sheetIndex = )
{
DataTable dt = new DataTable();
ISheet sheet = null;
IWorkbook iworkbook = null;
if (!isExcel2007)
{
sheet = (HSSFSheet)workbook.GetSheetAt(sheetIndex);
iworkbook = workbook;
}
else
{
sheet = (XSSFSheet)workbook2007.GetSheetAt(sheetIndex);
iworkbook = workbook;
}
System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); IRow headerRow = sheet.GetRow();
int cellCount = headerRow.LastCellNum; for (int j = ; j < cellCount; j++)
{
ICell cell = headerRow.GetCell(j);
dt.Columns.Add(cell.ToString());
} for (int i = (sheet.FirstRowNum + ); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
if (row == null)
continue;
DataRow dataRow = dt.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++)
{
ICell cell = row.GetCell(j);
if (cell != null)
{
if (cell.CellType == CellType.Numeric)
{
//NPOI中数字和日期都是NUMERIC类型的,这里对其进行判断是否是日期类型
if (HSSFDateUtil.IsCellDateFormatted(cell))//日期类型
{
dataRow[j] = cell.DateCellValue;
}
else//其他数字类型
{
dataRow[j] = cell.NumericCellValue;
}
}
else if (cell.CellType == CellType.Blank)//空数据类型
{
dataRow[j] = "";
}
else if (cell.CellType == CellType.Formula)//公式类型
{
HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(iworkbook);
dataRow[j] = eva.Evaluate(cell).StringValue;
}
else //其他类型都按字符串类型来处理
{
dataRow[j] = cell.StringCellValue;
}
}
} dt.Rows.Add(dataRow);
}
return dt;
} /// <summary>
/// 创建一个Sheet页
/// </summary>
/// <param name="Sheet">Sheet</param>
public void CreateSheet(Sheet sheetInfo)
{
if (string.IsNullOrWhiteSpace(sheetInfo.Name)) sheetInfo.Name = "Sheet" + workbook.NumberOfSheets + ;
HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(sheetInfo.Name);
int rowIndex = ; #region 新建表,填充表头,填充列头,样式
HSSFRow headerRow = (HSSFRow)sheet.CreateRow(rowIndex);
headerRow.HeightInPoints = ;
var columIndex = ;
foreach (var column in sheetInfo.Columns)
{
headerRow.CreateCell(columIndex).SetCellValue(column.Name);
if ("Red".Equals(column.ColorType))
headerRow.GetCell(columIndex).CellStyle = HeadStyle_red;
else
headerRow.GetCell(columIndex).CellStyle = HeadStyle;
//设置列宽
sheet.SetColumnWidth(columIndex, column.Width * );
sheet.SetColumnHidden(columIndex, column.Hidden);
columIndex++;
} #endregion
#region 填充内容
rowIndex = ; HSSFCellStyle contentStyle = (HSSFCellStyle)ContentStyle;
foreach (DataRow row in sheetInfo.DataSource.Rows)
{
HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);
var columnIndex = ;
//dataRow.RowStyle = ContentStyle;
foreach (var column in sheetInfo.Columns)
{
HSSFCell newCell = (HSSFCell)dataRow.CreateCell(columnIndex);
if (!sheetInfo.DataSource.Columns.Contains(column.Code))
{
newCell.SetCellValue("");
}
else
{
string drValue = row[column.Code].ToString(); switch (column.DataType.ToUpper())
{
case "S"://字符串类型
newCell.SetCellValue(drValue);
if ("Red".Equals(column.ColorType))
newCell.CellStyle = ContentStyle_red;//格式化显示
else
newCell.CellStyle = contentStyle;//格式化显示
break;
case "D"://日期类型
System.DateTime dateV;
System.DateTime.TryParse(drValue, out dateV);
newCell.SetCellValue(dateV);
newCell.CellStyle = contentStyle;//格式化显示
break;
case "B"://布尔型
bool boolV = false;
bool.TryParse(drValue, out boolV);
newCell.SetCellValue(boolV);
break;
case "I"://整型
int intV = ;
int.TryParse(drValue, out intV);
newCell.SetCellValue(intV);
break;
case "F"://浮点型
double doubV = ;
double.TryParse(drValue, out doubV);
newCell.SetCellValue(doubV);
break;
default:
newCell.SetCellValue(drValue);
break;
}
}
columnIndex++;
}
rowIndex++;
}
#endregion
} public void CreateSheet(DataTable dt, string sheetname)
{
Sheet sheet = new Sheet();
sheet.Name = sheetname;
List<Column> columns = new List<Column>();
for (int i = ; i < dt.Columns.Count; i++)
{
DataColumn col = dt.Columns[i];
Column column = new Column();
column.Code = col.ColumnName;
column.Name = col.ColumnName;
column.DataType = "S";
column.Width = ;
column.Hidden = false;
columns.Add(column);
}
sheet.Columns = columns;
sheet.DataSource = dt;
if (!isExcel2007)
{
this.CreateSheet(sheet);
}
else
{
this.CreateSheet2007(sheet);
}
} public void CreateSheet2007(Sheet sheetInfo)
{
if (string.IsNullOrWhiteSpace(sheetInfo.Name)) sheetInfo.Name = "Sheet" + workbook2007.NumberOfSheets + ;
XSSFSheet sheet = (XSSFSheet)workbook2007.CreateSheet(sheetInfo.Name); int rowIndex = ; #region 新建表,填充表头,填充列头,样式
XSSFRow headerRow = (XSSFRow)sheet.CreateRow(rowIndex);
headerRow.HeightInPoints = ;
var columIndex = ;
foreach (var column in sheetInfo.Columns)
{
headerRow.CreateCell(columIndex).SetCellValue(column.Name);
if ("Red".Equals(column.ColorType))
headerRow.GetCell(columIndex).CellStyle = HeadStyle_red;
else
headerRow.GetCell(columIndex).CellStyle = HeadStyle;
//设置列宽
sheet.SetColumnWidth(columIndex, column.Width * );
sheet.SetColumnHidden(columIndex, column.Hidden);
columIndex++;
} #endregion
#region 填充内容
rowIndex = ;
XSSFCellStyle contentStyle = (XSSFCellStyle)ContentStyle;
//XSSF contentStyle = (HSSFCellStyle)ContentStyle;
foreach (DataRow row in sheetInfo.DataSource.Rows)
{
XSSFRow dataRow = (XSSFRow)sheet.CreateRow(rowIndex);
var columnIndex = ;
//dataRow.RowStyle = ContentStyle;
foreach (var column in sheetInfo.Columns)
{
XSSFCell newCell = (XSSFCell)dataRow.CreateCell(columnIndex);
if (!sheetInfo.DataSource.Columns.Contains(column.Code))
{
newCell.SetCellValue("");
}
else
{
string drValue = row[column.Code].ToString(); switch (column.DataType.ToUpper())
{
case "S"://字符串类型
newCell.SetCellValue(drValue);
if ("Red".Equals(column.ColorType))
newCell.CellStyle = ContentStyle_red;//格式化显示
else
newCell.CellStyle = contentStyle;//格式化显示
break;
case "D"://日期类型
System.DateTime dateV;
System.DateTime.TryParse(drValue, out dateV);
newCell.SetCellValue(dateV);
newCell.CellStyle = contentStyle;//格式化显示
break;
case "B"://布尔型
bool boolV = false;
bool.TryParse(drValue, out boolV);
newCell.SetCellValue(boolV);
break;
case "I"://整型
int intV = ;
int.TryParse(drValue, out intV);
newCell.SetCellValue(intV);
break;
case "F"://浮点型
double doubV = ;
double.TryParse(drValue, out doubV);
newCell.SetCellValue(doubV);
break;
default:
newCell.SetCellValue(drValue);
break;
}
}
columnIndex++;
}
rowIndex++;
}
#endregion
}
/// <summary>
/// 保存
/// </summary>
/// <param name="filePath">文件路径</param>
public void SaveAs(string filePath)
{
using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = ; using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, , data.Length);
fs.Flush();
}
}
} /// <summary>
/// 获取Workbook的MemoryStream
/// </summary>
/// <returns></returns>
public MemoryStream GetMemoryStream()
{
MemoryStream ms = new MemoryStream();
if (!isExcel2007)
{
workbook.Write(ms);
ms.Flush();
ms.Position = ;
}
else
{
workbook2007.Write(ms);
}
return ms;
}
} public class Column
{
public string Code { get; set; }
public string Name { get; set; }
public string DataType { get; set; }
public int Width { get; set; }
public bool Hidden { get; set; }
public string ColorType { get; set; }
public Column() { }
public Column(string code, string name, string dataType, int width, bool hidden = false)
{
Code = code;
Name = name;
DataType = dataType;
Width = width;
Hidden = hidden;
}
} public class Sheet
{
public string Name { get; set; }
public List<Column> Columns { get; set; }
public DataTable DataSource { get; set; }
public Sheet() { }
public Sheet(string name, List<Column> columns, DataTable dataSource)
{
Name = name;
Columns = columns;
DataSource = dataSource;
}
} }

基于C#语言MVC框架NPOI控件导出Excel表数据的更多相关文章

  1. 基于C#语言MVC框架Aspose.Cells控件导出Excel表数据

    控件bin文件下载地址:https://download.csdn.net/download/u012949335/10610726 @{ ViewBag.Title = "xx" ...

  2. 基于存储过程的MVC开源分页控件--LYB.NET.SPPager

    摘要 现在基于ASP.NET MVC的分页控件我想大家都不陌生了,百度一下一大箩筐.其中有不少精品,陕北吴旗娃杨涛大哥做的分页控件MVCPager(http://www.webdiyer.com/)算 ...

  3. 基于存储过程的MVC开源分页控件

    基于存储过程的MVC开源分页控件--LYB.NET.SPPager 摘要 现在基于ASP.NET MVC的分页控件我想大家都不陌生了,百度一下一大箩筐.其中有不少精品,陕北吴旗娃杨涛大哥做的分页控件M ...

  4. Visual Basic 2012 借助DataGridView控件将Excel 2010数据导入到SQL server 2012

    (注:注释的颜色原本为绿色,在这里变为黑色,有点不便,但不会造成阅读影响.放入Visual Basic2012代码编辑器后会还原成绿色.) 摘  要:DataGridView控件作为数据传输的中介,只 ...

  5. datagridview控件--导出Excel

    dataGridView控件可以说很方便的显示了数据,而且对于修改和删除数据也很方便,我在前面的一篇博客中写到了如何去绑定数据到该控件上dataGridView控件--绑定数据方法,今天我将如何将数据 ...

  6. C# winform平台下使用spread控件导出excel表格

    //首先要引入两个控件:1.根据自己的office 版本在项目->添加引用->microsoft office object 12.0 library (2010版) //2.在.net中 ...

  7. 基于KO+bootstrap+MVC的分页控件

    JS: /// <reference path="../knockout-3.2.0.js" /> var ViewModel = function (data) { ...

  8. asp.net 控件 导出 excel

    //导出EXCEL protected void btnDaoChu_Click(object sender, EventArgs e) { HttpContext.Current.Response. ...

  9. webform 不实用office控件导出excel StringBuilder 类型拼接字符串表格导出excel

    StringBuilder sb = new StringBuilder(); sb.AppendLine("<meta http-equiv=\"Content-Type\ ...

随机推荐

  1. stuff函数(转)

    在上篇博文中提到了stuff函数 在这篇博文中对stuff函数进行了详解 本片博文系转载,但对原文顺序做了下调整 示例 以下示例在第一个字符串 abcdef 中删除从第 2 个位置(字符 b)开始的三 ...

  2. 嵌入式的SQL程序设计

    嵌入式的SQL程序设计 sql语句大全之嵌入式SQL 2017-01-18 16:00 来源:未知   嵌入式SQL 为了更好的理解嵌入式SQL,本节利用一个具体例子来说明.嵌入式SQL允许程序连接数 ...

  3. UI设计,你为什么不能把标题做的更明显呢?

    在设计中标题常常被重视,标题即是文案信息的精华提炼,那么如何能把标题在很多文案信息中脱颖而出就是设计师所要做的工作,前面的文章说过对比可以凸显主题,这期是在对比合理的前提下更进一步的处理方法,我们可以 ...

  4. 12月6日 被引入的jsp 页面,引入 js 要注意结束符 要用 </script> 而不是 />

    12月6日  被引入的jsp 页面,引入 js 要注意结束符 要用  </script> 而不是 />

  5. scrapy官方安装方法

    安装依赖 sudo apt-get install python-dev python-pip libxml2-dev libxslt1-dev zlib1g-dev libffi-dev libss ...

  6. 2018.07.03 HDU Rikka with Phi(线段树)

    Rikka with Phi Time Limit: 16000/8000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others) P ...

  7. 2018.09.18 atcoder Best Representation(kmp)

    传送门 思路简单不知为何调试了很久. 显然要么分成n个(所有字符相同),要么分成1个(原字符串无循环节),要么分成两个(有长度至少为2的循环节). 一开始以为可以直接hash搞定. 后来wa了几次之后 ...

  8. Linux下编译与调试

    gcc/g++编译器 对于.c格式的C文件,可以采用gcc或g++编译 对于 .cc..cpp格式的C++文件,应该采用g++进行编译 常用的选项: -c  表示编译源文件 -o  表示输出目标文件 ...

  9. HDU 1061 Rightmost Digit (快速幂取模)

    题意:给定一个数,求n^n的个位数. 析:很简单么,不就是快速幂么,取余10,所以不用说了,如果不会快速幂,这个题肯定是周期的, 找一下就OK了. 代码如下: #include <iostrea ...

  10. 理解Nodejs的Event Loop

    Node的“event loop”主要是用来处理高输出量的.这很神奇,这也是为什么node可以在单线程的情况下同时处理很多的后台操作.本文就会集中讲述event loop是怎么运行的,这样你可以可以使 ...