尝试将粗体应用于整行,但继续获得空引用 - NPOI

时间:2014-09-19 20:15:14

标签: c# npoi

我第一次将粗体应用于列,但我只想要一行而不是整列。所以我决定使用row.RowStyle做同样的事情。编译没有错误,但我得到的是运行时错误,其中显示r.RowStyle.SetFont(font);。我创建了一个类来处理与excel相关的所有内容,在本课程中我得到了这个错误(r.RowStyle.SetFont(font);):

处理了NullReferenceException

未将对象引用设置为对象的实例。

调试整个过程而不是null。我不明白为什么在使用RowStyle时出现此错误,当我使用CellStyle时,我没有收到该错误。

这是我的班级:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;   

using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;

using System.IO;


//works with everything related to excel
namespace takeMyTime_text
{
    class exelSheet
    {
            string exelPath; // where it's being saved

        HSSFWorkbook wb2 = new HSSFWorkbook();

        ISheet sheet;

        IRow r;

        IFont font;

        String[] headerTitles = { "Date", "In", "Out", "In", "Out", "Description" };

        // assing values to class variables
        public void getValues(string path, string worksheetName)
        {
            exelPath = path;
        }


        //excel header
        public void header()
        {
            #region set bold properties

            font = wb2.CreateFont();

            font.FontHeightInPoints = 11;

            font.FontName = "Arial";

            font.Boldweight = (short)FontBoldWeight.Bold;

            #endregion

            sheet = wb2.CreateSheet("test sheet");

            //se tiene que usar esto cada vez que vallas a escribir en el mismo row
            r = sheet.CreateRow(0);

            r.RowStyle.SetFont(font);

            for (int i = 0; i < headerTitles.Length; i++)
            {
                r.CreateCell(i).SetCellValue(headerTitles[i]);
            }
        }

        //excel footer
        public void footer(int row, int col, string totalHours, int row2, int col2)
        {
            //ws.Cells[row, col] = new Cell("Worked hours:");

            //ws.Cells[row2, col2] = new Cell(totalHours);

            //wb.Worksheets.Add(ws);

            //wb.Save(exelPath);            
        }

        // write the date on the excel file
        public void writeDate(DateTime dt, int col, int row)
        {
            r = sheet.CreateRow(row);

            r.CreateCell(col).SetCellValue(dt.Month + "/" + dt.Day + "/" + dt.Year);          
        }

        //write and value on a cel
        public void writeValues(string text, int col, int row)
        {
            //r = sheet.CreateRow(row);

            r.CreateCell(col).SetCellValue(text);           
        }

        //guarda la info en un excel
        public void writeToFile()
        {
            FileStream file = new FileStream(exelPath, FileMode.Create);

            wb2.Write(file);

            file.Close();
        }
    }
}

1 个答案:

答案 0 :(得分:5)

看起来你的RowStyle为null。请尝试以下方法:

var style = wb2.CreateCellStyle();
style.SetFont(font);

r = sheet.CreateRow(0);
r.RowStyle = style;