TypeInitializationException

Nov 26, 2009 at 8:30 AM

Hi

I get TypeInitializationException at this line "hssfworkbook = new HSSFWorkbook();" and I can't figure out what is wrong. I copied a example project from the downloaded package and here is the complete code:

using System;
using System.IO;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;

namespace Admin.Statistics
{
    public partial class Stats : System.Web.UI.Page
    {
        HSSFWorkbook hssfworkbook;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["fromDate"] != null && Request["toDate"] != null)
            {
                const string filename = "test.xls";
                Response.ContentType = "application/vnd.ms-excel";
                Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename));
                Response.Clear();

                InitializeWorkbook();
                GenerateData();
                Response.BinaryWrite(WriteToStream().GetBuffer());
                Response.End();
            }
        }

        void GenerateData()
        {
            HSSFSheet sheet1 = hssfworkbook.CreateSheet("Sheet1");

            sheet1.CreateRow(0).CreateCell(0).SetCellValue("This is a Sample");
            int x = 1;
            for (int i = 1; i <= 15; i++)
            {
                HSSFRow row = sheet1.CreateRow(i);
                for (int j = 0; j < 15; j++)
                {
                    row.CreateCell(j).SetCellValue(x++);
                }
            }
        }

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

        MemoryStream WriteToStream()
        {
            //Write the stream data of workbook to the root directory
            MemoryStream file = new MemoryStream();
            hssfworkbook.Write(file);
            return file;
        }
    }
}

 

Does anyone know what the problem could be?

 

/Best regards Daniel

 

Nov 30, 2009 at 9:06 AM

Hi again.

I figured out what the problem was. I forgot to include the NPOI.Util reference in the project. 

 

/Best regards Daniel