[The ASP.NET] NPOI produced using EXCEL

Abstract: [ASP.NET] NPOI produced using EXCEL


Foreword


NPOI is a quick read with third-party packages generate EXCEL EXCEL files, for the case of need to generate EXCEL report is very easy to use, the following brief use.

example


Step 1 Download NPOI Library

Please CodePlex to download NPOI Library, unzip the download is complete as follows:

There are some within the archive documentation can take a look at the other contains two examples for the sample file folder, bin that you want to join the project DLL file, which I use bin.net DLL file folder in 4.0, will join DLL reference to the new site.

Step 2 Create Report-like version

Use NPOI can own dynamically build EXCEL also be able to use EXCEL-like version of the file to generate reports based on this use I use pattern-profile way, first create a Office Excel file 2003 format will be displayed related field format set, as follows :

Good sample production at the site after the file into a little bit after the sub-directory with the addition of a Default.aspx page so that can start operating.

Step 3 written reports generated class

Next step is to start writing program, the following method for example can get the complete program, here only roughly explain ways:

InitReport () method

In InitReport process, to set the initialization report set as follows:

  • MaxCol : The total number of fields, thus a total of five examples of view EXCEL bar, but start to fill in so that from 0 4
  • StartRow : initial column, whereby the first example of the second term as the report title as the title bar so start from the third row, but also from the start so fill 2 0
  • ExportPath : generate file paths, such as to save the generated here will set the path EXCEL
  • ExportFileName : name of the generated file
  • TemplatePath : 样版档路径
  • TemplateFileName : 样版文件的名称
  • TemplateFilePath : 样版文件的完整路径
private void InitReport()
{
    MaxCol = 4;
    StartRow = 2;
    ExportPath = "~/Rpt/Export/";
    ExportFileName = "ProductReport.xls";
    TemplatePath = "~/Rpt/Template/";
    TemplateFileName = "TemplateReport.xls";
    TemplateFilePath = TemplatePath + TemplateFileName;
}

LoadSheet() 方法

在LoadSheet方法中,将会开启指定的样板档,其中 HssfWorkbook.GetSheetAt(0) 这段主要为取得样版中指定的Sheet Index Number,想用Sheet名称取得话可以改用 GetSheet(string name) 方法。

因为之后要设定新增列的格式跟字体,所以额外建立 CreateCellStyle 与 CreateFont 对象,之所以不放在InserNewRow()法中产生是因为如每产生一列就新增模式对象,会造成Excel资源消耗而发生模式跑掉的问题。

private void LoadSheet()
{
    FileStream file = new FileStream(HttpContext.Current.Server.MapPath(TemplateFilePath), FileMode.Open, FileAccess.Read); // 开启读取样版档
    HssfWorkbook = new HSSFWorkbook(file);
    Sheet = HssfWorkbook.GetSheetAt(0); // 取得Index为0的Sheet
    CellStyle = HssfWorkbook.CreateCellStyle(); // 产生字段模式设定
    Font = HssfWorkbook.CreateFont();   // 产生字体模式设定
}

InsertNewRow() 方法

在InsertNewRow方法中,主要的作用就是动态产生一列新列,产生后设定该列的模式与字体等等后回传该列让后续操作。

private IRow InsertNewRow()
{
    IRow row;
    ICell cell;
    Sheet.ShiftRows(StartRow, Sheet.LastRowNum, 1);
    row = Sheet.GetRow(StartRow);   // 取得列
    if (row == null)
        row = Sheet.CreateRow(StartRow);    // 若无该列则产生新列
    for (int i = 0; i <= MaxCol; i++)
    {
        cell = row.CreateCell(i);   // 产生字段
        // 设定字段框线
        CellStyle.BorderBottom = BorderStyle.THIN;
        CellStyle.BorderLeft = BorderStyle.THIN;
        CellStyle.BorderRight = BorderStyle.THIN;
        CellStyle.BorderTop = BorderStyle.THIN;
        // 设定对齐方式
        CellStyle.Alignment = HorizontalAlignment.LEFT; // 水平
        CellStyle.VerticalAlignment = VerticalAlignment.CENTER; // 垂直
        CellStyle.WrapText = true; // 是否自动换行
        // 设定字体
        Font.FontName = "标楷体";
        Font.FontHeightInPoints = 12;

        CellStyle.SetFont(Font);
        cell.CellStyle = CellStyle;
    }
    StartRow++;
    return row;
}

ReportLogic() 方法

在ReportLogic方法中,主要就是报表逻辑的撰写,此处将依照要产生的报表需求撰写相关程序,直接取得样版中字段位置的方法就是使用 Sheet.GetRow(0).GetCell(0).SetCellValue("") 方法,如需要使用Excel的公式的话可以使用 row.GetCell(0).SetCellFormula(string formula) 方法,另外可以看到报表内容部分就是跑回圈取得来源数据后反复进行[ 新增列 > 指定列的字段值 ]动作。

private void ReportLogic()
{
    // 报表标题
    Sheet.GetRow(0).GetCell(0).SetCellValue("产品报表");

    // 报表内容
    foreach (ProductDao.ProductEntity entity in GetData())
    {
        IRow row = InsertNewRow(); // 插入新列

        row.GetCell(0).SetCellValue(entity.ProductID);
        row.GetCell(1).SetCellValue(entity.ProductName);
        row.GetCell(2).SetCellValue(entity.ProductPrice);
        row.GetCell(3).SetCellValue(entity.ProductNumber);
        row.GetCell(4).SetCellFormula(string.Format("C{0}*D{0}", StartRow));
    }
}

ExportExcel方法与SaveExcel方法

最后一步当然要将产生的数据输出,这边提供了两种输出方法

ExprotExcel() 方法为直接将网页转换ContentType后输出,Client端就可以直接跳出EXCEL下载窗口。

SaveExcel() 方法为将先文件保存在Server的主机上并且也回传文件路径回来。

public void ExportExcel()
{
    // 设定网页ContentType
    HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
    HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", ExportFileName));
    HttpContext.Current.Response.Clear();
    // 读取样版数据
    LoadSheet();
    // 执行报表逻辑
    ReportLogic();  
    // 报表写入数据流
    MemoryStream file = new MemoryStream();
    HssfWorkbook.Write(file);
    // 输出报表跳出下载窗口
    HttpContext.Current.Response.BinaryWrite(file.GetBuffer());
    HttpContext.Current.Response.End();
}

public string SaveExcel()
{
    // 读取样版数据
    LoadSheet();
    // 执行报表逻辑
    ReportLogic();  
    // 保存文件路径
    string saveFilePath = ExportPath + ExportFileName;
    // 报表写入数据流
    FileStream file = new FileStream(HttpContext.Current.Server.MapPath(saveFilePath), FileMode.Create);
    HssfWorkbook.Write(file);
    file.Close();
    // 回传产出文件路径
    return saveFilePath;
}

以上就是一个基本的 NPOI 动态产生 EXCEL 的使用范例,基本上抓下来后依照这种方式作或添加新设定就可以产生EXCEL,而针 NPOI 对于 EXCEL 的操作方法还有很多种设定,例如合并栏、其它函数操作、画图形等等的功能可以去参考 NPOI 官方文档网站查询。

结果:

范例程序


TNPOI.rar

参考数据


官方网站




以上文章叙述如有错误及观念不正确,请不吝啬指教
如有侵权内容也请您与我反应~谢谢您 :)

原文:大专栏  [ASP.NET] 使用NPOI产生EXCEL


Guess you like

Origin www.cnblogs.com/chinatrump/p/11491095.html