//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;
}
