使用開源NPOI導出簡單excel文件


 

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM