详细教程: http://blog.csdn.net/xxs77ch/article/details/50216033

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Reflection;
using WSC.Common;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.SS.Util; namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
private string constr = ConfigurationManager.AppSettings["LocalConnectionString"];
protected void Page_Load(object sender, EventArgs e)
{ }
private DataTable getDT(string fid)
{
DataTable dt = new DataTable();
if (string.IsNullOrEmpty(fid))
Response.Write("");
else
{
SQLHelper s = new SQLHelper(constr);
string sql = @"";
dt = s.Query(sql);
}
return dt;
} protected void Button1_Click(object sender, EventArgs e)
{
string fid = "001";
DataTable datas = getDT(fid);
if (datas.Rows.Count < )
Response.Write("<script type=\"text/javascript\">alert('无相关信息,请先维护!')</script>");
else
{
ExportExcel(datas, "nameExcel", "sheetName");
}
} /// <summary>
/// DataTable导出Excel
/// </summary>
/// <param name="dt">datatable数据源</param>
/// <param name="strFileName">文件名</param>
/// <param name="strSheetName">工作簿名</param>
public void ExportExcel(DataTable dt, string strFileName, string strSheetName)
{
IWorkbook book = new HSSFWorkbook();
ISheet sheet = book.CreateSheet("sheetName");
IRow dataRow = sheet.CreateRow();//创建一个对象,该对象表示着第一行(在createRow方法中,参数0能够得到体现)。
ICell dataCell = dataRow.CreateCell();//创建一个对象,该对象表示着第一的第一列(在createCell方法中,参数0能够得到体现)。 #region 头部
dataCell.SetCellValue("头部信息");
IFont font = book.CreateFont();//创建字体样式。这里只是创建了一个字体样式,
ICellStyle style = book.CreateCellStyle();//创建一个样式 font.FontName = "宋体";
font.Boldweight = short.MaxValue;
font.FontHeightInPoints = ; font.Color = NPOI.HSSF.Util.HSSFColor.Grey50Percent.Index;
style.SetFont(font);//将字体样式加到样式对象中去。
dataCell.CellStyle = style;//将样式作用于dataCell对象,这个对象前面有提到过,指的是第一行第一列
sheet.SetColumnWidth(, * );//设置第0行的列宽是18*256(256指的是字符)
sheet.SetColumnWidth(, * );//设置第1行列宽是50*256
sheet.SetColumnWidth(, * );
sheet.SetColumnWidth(, * ); ICellStyle style2 = book.CreateCellStyle();
IFont font2 = book.CreateFont();
font2.FontHeightInPoints = ;
font2.Color = NPOI.HSSF.Util.HSSFColor.Black.Index; style2.SetFont(font2);
sheet.AddMergedRegion(new CellRangeAddress(, , , ));//合并单元格,前两位表示起始行,结束行。后两个表示起始列,结束列。
dataCell = dataRow.CreateCell();
style2.Alignment = HorizontalAlignment.Center;
style2.VerticalAlignment = VerticalAlignment.Center;
dataCell.SetCellValue("设置值");
dataCell.CellStyle = style2; ICellStyle style3 = book.CreateCellStyle();
dataRow = sheet.CreateRow();
dataCell = dataRow.CreateCell();
dataCell.SetCellValue("设置值");
sheet.AddMergedRegion(new CellRangeAddress(, , , ));
style3.Alignment = HorizontalAlignment.Center;
style3.VerticalAlignment = VerticalAlignment.Center;
dataCell.CellStyle = style3; sheet.AddMergedRegion(new CellRangeAddress(, , , ));
dataCell = dataRow.CreateCell();
dataCell.SetCellValue("设置值");
ICellStyle styleType = book.CreateCellStyle();
styleType.Alignment = HorizontalAlignment.Right;
styleType.VerticalAlignment = VerticalAlignment.Center;
dataCell.CellStyle = styleType;
ICellStyle styleMachineType1 = book.CreateCellStyle();
styleMachineType1.VerticalAlignment = VerticalAlignment.Center;
styleMachineType1.Alignment = HorizontalAlignment.Right;
sheet.AddMergedRegion(new CellRangeAddress(,,,));
dataCell = dataRow.CreateCell();
dataCell.SetCellValue("设置值");
ICellStyle styleMachineType0 = book.CreateCellStyle();
styleMachineType0.Alignment = HorizontalAlignment.Left;
dataCell.CellStyle = styleMachineType0; dataRow = sheet.CreateRow();
dataCell = dataRow.CreateCell();
dataCell.SetCellValue("4H.15D36.A01");
ICellStyle styleMachineType = book.CreateCellStyle();
styleMachineType.Alignment = HorizontalAlignment.Left;
dataCell.CellStyle = styleMachineType; //dataRow = sheet.CreateRow(2);
dataCell = dataRow.CreateCell();
dataCell.SetCellValue("设置值"); dataRow = sheet.CreateRow();
dataCell = dataRow.CreateCell();
dataCell.SetCellValue("B156HAN");
ICellStyle styleMachineType3 = book.CreateCellStyle();
styleMachineType3.Alignment = HorizontalAlignment.Left;
dataCell.CellStyle = styleMachineType3; #endregion #region 中间
dataRow = sheet.CreateRow();
ICellStyle style4 = book.CreateCellStyle();
IFont font3 = book.CreateFont();
font3.FontHeightInPoints = ;
style4.SetFont(font3);
style4.Alignment = HorizontalAlignment.Center;
style4.VerticalAlignment = VerticalAlignment.Center; string strColumns = "第一列,第二列,第三列";
string[] strArry = strColumns.Split(',');
for (int i = ; i < strArry.Length; i++)
{
dataRow.CreateCell(i).SetCellValue(strArry[i]);
dataRow.GetCell(i).CellStyle = style4;//设置样式
} ICellStyle bodyStyle = book.CreateCellStyle();
bodyStyle.Alignment = HorizontalAlignment.Center;
for (int i = ; i < dt.Rows.Count; i++)
{
dataRow = sheet.CreateRow(i + );
for (int j = ; j < ; j++)
{
string ValueType = "";
string Value = "";
if (dt.Rows[i][j].ToString() != null)
{
ValueType = dt.Rows[i][j].GetType().ToString();
Value = dt.Rows[i][j].ToString();
}
switch (ValueType)
{
case "System.String"://字符串类型
if ((j == ) && (Value != "OK"))
{
dataRow.CreateCell(j).SetCellValue("OK");
//dataRow.CreateCell(j + 1).CellStyle = bodyStyle;
//dataRow.CreateCell(j + 1).SetCellValue(Value);
dataCell = dataRow.CreateCell(j + );
dataCell.CellStyle = bodyStyle;
dataCell.SetCellValue(Value); }
else
{
dataRow.CreateCell(j).SetCellValue(Value);
}
break;
case "System.DateTime"://日期类型
System.DateTime dateV;
System.DateTime.TryParse(Value, out dateV);
dataRow.CreateCell(j).SetCellValue(dateV);
break;
case "System.Boolean"://布尔型
bool boolV = false;
bool.TryParse(Value, out boolV);
dataRow.CreateCell(j).SetCellValue(boolV);
break;
case "System.Int16"://整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = ;
int.TryParse(Value, out intV);
dataRow.CreateCell(j).SetCellValue(intV);
break;
case "System.Decimal"://浮点型
case "System.Double":
double doubV = ;
double.TryParse(Value, out doubV);
dataRow.CreateCell(j).SetCellValue(doubV);
break;
case "System.DBNull"://空值处理
dataRow.CreateCell(j).SetCellValue("");
break;
default:
dataRow.CreateCell(j).SetCellValue("");
break;
}
if (j != )
dataRow.GetCell(j).CellStyle = bodyStyle;
//dataRow.GetCell(j).CellStyle = style; //sheet.SetColumnWidth(j, (Value.Length + 10) * 256);//设置宽度
}
} #endregion #region 底部
dataRow = sheet.CreateRow( + dt.Rows.Count);
dataCell = dataRow.CreateCell();
dataCell.SetCellValue("注:");
ICellStyle styleFoot = book.CreateCellStyle();
styleFoot.Alignment = HorizontalAlignment.Right;
styleFoot.VerticalAlignment = VerticalAlignment.Top;
IFont fontFoot = book.CreateFont();
fontFoot.FontHeightInPoints = ;
styleFoot.SetFont(fontFoot);
dataCell.CellStyle = styleFoot;
sheet.AddMergedRegion(new CellRangeAddress( + dt.Rows.Count, + dt.Rows.Count + , , ));
sheet.AddMergedRegion(new CellRangeAddress( + dt.Rows.Count, + dt.Rows.Count, , ));
sheet.AddMergedRegion(new CellRangeAddress( + dt.Rows.Count, + dt.Rows.Count, , ));
sheet.AddMergedRegion(new CellRangeAddress( + dt.Rows.Count, + dt.Rows.Count, , ));
sheet.AddMergedRegion(new CellRangeAddress( + dt.Rows.Count, + dt.Rows.Count, , ));
dataRow = sheet.CreateRow( + dt.Rows.Count);
dataCell = dataRow.CreateCell();
dataCell.SetCellValue("设置值");
dataRow = sheet.CreateRow( + dt.Rows.Count);
dataCell = dataRow.CreateCell();
dataCell.SetCellValue("设置值");
dataRow = sheet.CreateRow( + dt.Rows.Count);
dataCell = dataRow.CreateCell();
dataCell.SetCellValue("设置值");
dataRow = sheet.CreateRow( + dt.Rows.Count);
dataCell = dataRow.CreateCell();
dataCell.SetCellValue("设置值");
#endregion
     #region 插入图片
byte[] bytes = System.IO.File.ReadAllBytes(@"F:\gch.jpg");//写成流
int pictureIdx = book.AddPicture(bytes, PictureType.PNG);//book是之前创建工作簿的名字
HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();//sheet是之前创建的表单
HSSFClientAnchor anchor = new HSSFClientAnchor(, , , , , , , );//设置图片的尺寸及大小
HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
pict.Resize();
#endregion
//关于HSSFClientAnchor(dx1,dy1,dx2,dy2,col1,row1,col2,row2)的参数,有必要在这里说明一下:
//dx1:起始单元格的x偏移量,如例子中的255表示直线起始位置距A1单元格左侧的距离;
//dy1:起始单元格的y偏移量,如例子中的125表示直线起始位置距A1单元格上侧的距离;
//dx2:终止单元格的x偏移量,如例子中的1023表示直线起始位置距C3单元格左侧的距离;
//dy2:终止单元格的y偏移量,如例子中的150表示直线起始位置距C3单元格上侧的距离;
//col1:起始单元格列序号,从0开始计算;
//row1:起始单元格行序号,从0开始计算,如例子中col1=0,row1=0就表示起始单元格为A1;
//col2:终止单元格列序号,从0开始计算;
//row2:终止单元格行序号,从0开始计算,如例子中col2=2,row2=2就表示起始单元格为C3;
一个有关NPOI的demo:http://blog.csdn.net/chinajiyong/article/details/9187485
            MemoryStream ms = new MemoryStream();
book.Write(ms);
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8)));
Response.BinaryWrite(ms.ToArray());
Response.End();
book = null;
ms.Close();
ms.Dispose();
}
}
}

NPOI 2.0版本的使用的更多相关文章

  1. NPOI 2.0 Excel读取显示

    NPOI 2.0 Excel读取显示   最近接到需求,需要把excel表格里的数据原样展示到web页面,主要是满足随意跨行跨列. 之前用过一点NPOI,不过接触的不太多,趁这次机会再熟悉一下.由于操 ...

  2. .NET Core 2.0版本预计于2017年春季发布

    英文原文: NET Core 2.0 Planned for Spring 2017 微软项目经理 Immo Landwerth 公布了即将推出的 .NET Core 2.0 版本的细节,该版本预计于 ...

  3. 纪念BLives 1.0版本发布

    历时两个多月的时间,BLives程序1.0发布,在开发程序期间自己经历了很多,考试,恋爱,学业,自己很纠结 很伤心,有时候很无助,为了让自己有事干,我在考试备考期间去设计程序- -#,虽然程序设计的一 ...

  4. 【vuejs小项目——vuejs2.0版本】单页面搭建

    http://router.vuejs.org/zh-cn/essentials/nested-routes.html 使用嵌套路由开发,这里会出错主要把Vue.use(VueRouter);要进行引 ...

  5. geotrellis使用(二十)geotrellis1.0版本新功能及变化介绍

    目录 前言 变化情况介绍 总结 一.前言        之前版本是0.9或者0.10.1.0.10.2,最近发现更新成为1.0.0-2077839.1.0应该也能称之为正式版了吧.发现其中有很多变化, ...

  6. 【原】迎接微信winphone 5.0 版本的IE10样式兼容

    微信 Android 5.1 和 iPhone 5.1 已正式发布了,据说本12月底,微信将推出 Winphone 5.0版本,全面支持微信支付,它绑定 IE10 浏览器,那么做微信公众号的 H5 页 ...

  7. Mirantis OpenStack 8.0 版本大概性分析

    作为 OpenStack 领域标杆性企业之一的 Mirantis 在2016年3月初发布了最新的 MOS 8.0 版本.本文试着基于公开资料进行一些归纳分析. 1. 版本概况 1.1 概况 社区版本: ...

  8. 微信快速开发框架(六)-- 微信快速开发框架(WXPP QuickFramework)V2.0版本上线--源码已更新至github

    4月28日,已增加多媒体上传及下载API,对应MediaUploadRequest和MediaGetRequest ------------------------------------------ ...

  9. c#.Net:Excel导入/导出之NPOI 2.0简介

      NPOI 2.0+主要由SS, HPSF, DDF, HSSF, XWPF, XSSF, OpenXml4Net, OpenXmlFormats组成,具体列表如下: 资料来自:百度百科   Ass ...

随机推荐

  1. 如何使用PL/SQL进行远程数据库连接

    1.先找到Oracle数据库的安装地址然后找到network->ADMIN->tnsnames.ora文件 2.添加下面文件到tnsnames.ora文件中去,红色部分是需要修改的部分   ...

  2. W5500 keep-alive的用途与用法--新华龙电子

    大家是否遇到过这样的问题,W5500作为服务器已经建立连接,突然网线掉了,然后再去连接W5500,就连不上了.为什么?下面对这个问题进行解释说明,并提出解决办法. 图1中的上位机程序作为客户端,连接W ...

  3. 基于Windows服务器集群的Redis主从配置指南

    前段时间一个项目因并发量大.因防止宕机做了主从备份,首页的表连接查询又非常的耗时.故此拿出利器Redis缓存这个查询结果,并随着用户操作而更新. 因官方目前只有linux版,Windows版下载:  ...

  4. printf()输出

    printf()函数是式样化输出函数, 一般用于向准则输出设备按规定式样输出消息.正在编写步骤时经常会用到此函数.printf()函数的挪用式样为: printf("<式样化字符串&g ...

  5. 如何在IDEA上创建Spring MVC项目

    对于刚刚从eclipse.myeclipse转到IDEA工具,在搭建项目遇到了一些问题,所以让我来分享我的搭建过程. 建议大家准备java环境.IDEA工具.tomcat.maven了,还有我是win ...

  6. oracle修改字段长度

    alter table 表名 modify (字段名 字段类型长度);alter table cachemsg modify (callernum varchar(40));

  7. C#遍历集合与移除元素的方法

    如果用foreach,会造成被遍历的集合更改后带来异常问题. 此时,用for循环可有效的解决这个问题. for(int i=0;i<List.Count;i++) { if(条件是真) { Li ...

  8. 调用百度地图API出现 error inflating class com.baidu.mapapi.map.mapview

    问题如下 本来以为解决了,但后来重新运行了一下,又坏了,然后改成原来的样子,又好了. 结果就是:对不住了各位看官,没找到解决办法,不过经测试有个地方,可能在程序运行时,出现error inflatin ...

  9. IS A 和 HAS A的区别

    IS A:一般是用作继承或者接口类.比如:中国人和外国人都是人,重点在:是一个... . HAS A:一般用作对象和他的成员的从属关系.比如:中国人和外国人都有眼睛.耳朵.嘴巴.重点在:有一个... ...

  10. my sql中join的操作

    SQL标准中的Join的类型:  首先,设置表employees和department的数据为:  1.inner join … on操作类型 内连接inner join是基于连接谓词将两张表(如A和 ...