之前在C#网站或Webservice程序中一直使用COM组件的方式导出Excel文件,但是经常会出现调试成功,但是部署到服务器之后就失败的现象。如果服务器不是自己的,而要你到甲方那里去部署,出现这种现象就尴尬了。后来发现NPOI插件非常好用,这里总结一下。
首先到NPOI官网上下载dll,链接http://npoi.codeplex.com/downloads/get/1572743,然后解压并添加引用,这就不用上图了吧。
下面是对NPOI常用方法做的一个封装类,可以直接使用。
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace ExcelHelper
{
public class ExcelHelp
{
public static NPOI.HSSF.UserModel.HSSFWorkbook obook;
public static NPOI.SS.UserModel.ISheet osheet;
///
/// 构造函数,初始化表单对象
///
///
///
public ExcelHelp()
{
obook = new NPOI.HSSF.UserModel.HSSFWorkbook();
osheet = obook.CreateSheet("sheet1");
}
///
/// 合并单元格
///
/// 左上角单元格行标(从0开始,下同)
/// 左上角单元格列标
/// 右下角单元格行标
/// 右下角单元格列标
public void Merge( int r1,int c1,int r2,int c2)
{
osheet.AddMergedRegion(new CellRangeAddress(r1, c1, r2, c2));
}
///
/// 设置单元格内容
///
/// 单元格行标(从0开始,下同)
/// 单元格列标
/// 写入内容
public void SetValue( int r, int c, object o)
{
if (o != null)
{
if(r<=osheet.LastRowNum)
{
IRow row = osheet.GetRow(r);
if (row == null)
{
row = osheet.CreateRow(r);
row.HeightInPoints = 14;
}
if(c<=row.LastCellNum)
{
ICell cell = row.GetCell(c);
cell.SetCellValue(o.ToString());
}
else
{
for(int j=row.LastCellNum;j
/// 设置行高
///
/// 行数
/// 高度
public void SetRowHeight(int r,int height)
{
if (r <= osheet.LastRowNum)
{
IRow row = osheet.GetRow(r);
if (row != null)
{
row.HeightInPoints = height;
}
}
}
///
/// 设置字体宽度
///
/// 列标
/// 宽度值(例如设置为1,表示一个英文字符的宽度)
public void SetCollumWdith(int c, int width)
{
osheet.SetColumnWidth(c, 256 * width);
}
///
/// 设置单元格对齐方式
///
/// 行标
/// 列标
/// 对齐方式('L',左对齐;'C'居中;'R'右对齐)
public void SetCellAlignment(int r, int c, char align)
{
if(r<=osheet.LastRowNum)
{
IRow row = osheet.GetRow(r);
if(row!=null)
{
if(c<=row.LastCellNum)
{
ICell cell = row.GetCell(c);
ICellStyle style = cell.CellStyle;
//设置单元格的样式:水平对齐居中
if (align == 'C')
style.Alignment = HorizontalAlignment.Center;
else if (align == 'L')
style.Alignment = HorizontalAlignment.Left;
else if (align == 'R')
style.Alignment = HorizontalAlignment.Right;
cell.CellStyle = style;
}
}
}
}
///
/// 设置字体样式
///
/// 行标
/// 列标
/// 字体大小,0为默认
/// 字体样式(‘B’加粗,‘I’斜体)
/// 字体颜色('R'红,'B'蓝,'G'绿,'Y'黄,'P'粉,'O'橙,'W'白)
public void SetCellFont(int r, int c,int size, char f,char color)
{
if (r <= osheet.LastRowNum)
{
IRow row = osheet.GetRow(r);
if (row != null)
{
if (c <= row.LastCellNum)
{
ICell cell = row.GetCell(c);
ICellStyle style = cell.CellStyle;
//新建一个字体样式对象
IFont font = obook.CreateFont();
//设置字体大小
if(size>0)
font.FontHeightInPoints = Convert.ToInt16(size);
switch (f)
{
case 'B':
{
//设置字体加粗样式
font.IsBold = true;
} break;
case 'I':
{
//设置字体加粗样式
font.IsItalic = true;
} break;
}
switch (color)
{
case 'R': { font.Color = HSSFColor.Red.Index; } break;
case 'B': { font.Color = HSSFColor.Blue.Index; } break;
case 'G': { font.Color = HSSFColor.Green.Index; } break;
case 'Y': { font.Color = HSSFColor.Yellow.Index; } break;
case 'P': { font.Color = HSSFColor.Pink.Index; } break;
case 'O': { font.Color = HSSFColor.Orange.Index; } break;
case 'W': { font.Color = HSSFColor.White.Index; } break;
}
//使用SetFont方法将字体样式添加到单元格样式中
style.SetFont(font);
//将新的样式赋给单元格
cell.CellStyle = style;
}
}
}
}
///
/// 写入到Excel文档
///
///
///
///
public bool ExportToExcel(string path)
{
try
{
// 写入到客户端
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
obook.Write(fs);
}
return true;
}
catch { return false; }
}
public void Dispose()
{
obook.Close();
GC.Collect();
}
}
}
下面是调用方法,很简单了
ExcelHelper.ExcelHelp myexcel = new ExcelHelper.ExcelHelp();
try
{
myexcel.Merge(0, 0, 0, 3);
myexcel.SetValue(0, 0, "你好");
myexcel.SetRowHeight(0, 25);
myexcel.SetCellAlignment(0, 0, 'C');
myexcel.SetCellFont(0, 0, 20,'B','R');
myexcel.SetValue(3, 0, "你好");
myexcel.SetValue(10, 5, "你好");
myexcel.SetCollumWdith(4, 20);
myexcel.ExportToExcel("D:\\aaaabc.xls");
}
catch { }
finally { myexcel.Dispose(); }
注意,这里是winform的调用方法,如果是网页(asp.net)导出,函数ExportToExcel应该改写为下面的形式:
System.IO.MemoryStream ms = new System.IO.MemoryStream();
obook.Write(ms);
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
Response.BinaryWrite(ms.ToArray());
book = null;
ms.Close();
ms.Dispose();