详细教程: 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. 开源项目大全 >> ...

    http://www.isenhao.com/xueke/jisuanji/kaiyuan.php   监控系统-Nagios 网络流量监测图形分析工具-Cacti 分布式系统监视-zabbix 系统 ...

  2. 在 Hibernate 中出现 database product name cannot be null 时怎么解决?

    今 天在做一个SH项目结合的时候忽然出现了,这样的错误,我开始也不知道怎么办,便上网查,看一些高手回答都是说,检查 hibernate.cfg.xml 这个配置文件,或是一些其它的配置,于是我便看了一 ...

  3. how to enable remote access for root user

    GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password' WITH GRANT OPTION;

  4. tomcat7 ajax请求服务中文乱码

    在确保请求服务编码格式为utf-8的情况下,确保tomcat的配置 <Connector connectionTimeout="20000" port="8080& ...

  5. 虚拟机下linux安装mysql,apache和php

    由于腿伤了,卧床在家折腾下linux,尝试用虚拟机装mysql,apche和php.中间各种波折,装了好几天,觉得有些经验还是要记录下来,让自己别忘了:) 按照下面这篇文章的方法,基本可以顺利安装成功 ...

  6. iOS CoreAnimate 动画实现

    这里主要讲的是使用CoreAnimate实现所需的动画. 先上官网的介绍:https://developer.apple.com/library/ios/documentation/Cocoa/Con ...

  7. nodeJs 模块cookie-session api文档中文翻译,偶自己翻译的

    原文英文文档链接点击 说明 简单的 基于cookie的 session中间件 安装 它是一个可以用npm注册的node模块,可以通过npm install命令安装 npm install cookie ...

  8. sellsa

    我看见天空很蓝 就像你在我身边的温暖 生命有太多遗憾 人越成长越觉得孤单 我很想飞 多远都不会累 才明白爱得越深心就会越痛 我只想飞 在我的天空飞 我知道你会在我身边 回忆的画面 记录的语言 爱始终是 ...

  9. linux基础命令之:vi模式下查找和替换

    一.查找 查找命令 /pattern<Enter> :向下查找pattern匹配字符串 ?pattern<Enter>:向上查找pattern匹配字符串 使用了查找命令之后,使 ...

  10. PHP集成百度Ueditor 1.4.3

    下载安装 1.首先到官网下载最新版的UE1.4.3UE官方下载地址:http://ueditor.baidu.com/website/download.html#ueditor 这里我下载的是1.4. ...