//NPOI 函式庫
using NPOI;
using NPOI.DDF;
using NPOI.HPSF;
using NPOI.HSSF;
using NPOI.POIFS;
using NPOI.SS;
using NPOI.Util;
using NPOI.HSSF.UserModel;//HSSFWorkbook类
using NPOI.SS.UserModel;
using NPOI.SS.Util;
//NPOI 函式庫;
using System.IO;
这里涉及合并单元格的功能,实现如下:
string filename = "抄表情况.xls";
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename));
context.Response.Clear();
//InitializeWorkbook
InitializeWorkbook();
//GenerateData
ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
//sheet1.CreateRow(0).CreateCell(0).SetCellValue("抄表情况");
//写入总标题,合并居中
IRow row = sheet1.CreateRow(0);
ICell cell = row.CreateCell(0);
cell.SetCellValue("抄表情况");
ICellStyle style = hssfworkbook.CreateCellStyle();
style.Alignment = HorizontalAlignment.CENTER;
IFont font = hssfworkbook.CreateFont();
font.FontHeight = 20 * 20;
style.SetFont(font);
cell.CellStyle = style;
sheet1.AddMergedRegion(new CellRangeAddress(0, 0, 0, 20));
int r_count = dt.Rows.Count;
int c_count = dt.Columns.Count;
//插入列标题
row = sheet1.CreateRow(1);
for (int x = 0; x < c_count; x++)
{
cell = row.CreateCell(x);
cell.SetCellValue(dt.Columns[x].ColumnName);
}
//插入查询结果
for (int i = 0; i < r_count; i++)
{
//IRow row = sheet1.CreateRow(i);
row = sheet1.CreateRow(i+2);//从第二行开始
for (int j = 0; j < c_count; j++)
{
row.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString());
}
}
//Write the stream data of workbook to the root directory
MemoryStream file = new MemoryStream();
hssfworkbook.Write(file);
context.Response.BinaryWrite(file.GetBuffer());
context.Response.End();
附:
以下包括调用方法InitializeWorkbook和定义全局HSSFWorkbook对象hssfworkbook
HSSFWorkbook hssfworkbook;
void InitializeWorkbook()
{
hssfworkbook = new HSSFWorkbook();
////create a entry of DocumentSummaryInformation
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "NPOI Team";
hssfworkbook.DocumentSummaryInformation = dsi;
////create a entry of SummaryInformation
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Subject = "NPOI SDK Example";
hssfworkbook.SummaryInformation = si;
}