简体   繁体   English

生成Excel文件时,NPOI无法评估公式

[英]NPOI not being able to evaluate formula when excel file is generated

I have created excel file from data table using NPOI library . 我已经使用NPOI库从数据表创建了excel文件。 Excel file is created but formula is not evaluated. Excel文件已创建,但未评估公式。 This is first time i am using NPOI lib. 这是我第一次使用NPOI库。

After lot of google search i found few code snippet which i used in my code to evaluate formula but no luck still. 经过大量的google搜索,我发现了一些代码片段,这些片段在我的代码中用于评估公式,但是仍然没有运气。

This routine populate data table with random numeric values and dynamically composed formulas. 此例程使用随机数值和动态组成的公式填充数据表。 my data table screen shot attached here data table screen shot 我的数据表屏幕截图此处附有数据表屏幕截图

public DataTable GetDataTable()
{
    string strSum = "", strColName, strImmediateOneUp = "", strImmediateTwoUp = "";

    int startsum = 0;
    int currow = 0;
    bool firstTimeSum = true;

    int NumRows = 6;
    int NumColumns = 5;

    DataTable dt = new DataTable();

    for (int col = 0; col < NumColumns; col++)
    {
        strColName = GenerateColumnText(col);
        DataColumn datacol = new DataColumn(strColName, typeof(object));
        dt.Columns.Add(datacol);
    }


    for (int row = 0; row < NumRows; row++)
    {
        dt.Rows.Add();

        for (int col = 0; col < NumColumns; col++)
        {
            if (row < 2)
            {
                dt.Rows[row][col] = Convert.ToInt32(new Random().Next(1, NumRows));
            }
            else
            {
                if (firstTimeSum)
                {
                    if (row - currow == 2)
                    {
                        currow = row;
                        startsum = 0;
                        firstTimeSum = false;
                    }
                    else
                    {
                        startsum = 1;
                    }
                }
                else
                {
                    if (row - currow == 3)
                    {
                        currow = row;
                        startsum = 0;
                    }
                }


                if (startsum == 0)
                {
                    strColName = GenerateColumnText(col);
                    strImmediateOneUp = strColName + ((row + 1) - 1).ToString();
                    strImmediateTwoUp = strColName + ((row + 1) - 2).ToString();
                    strSum = string.Format("=SUM({0}:{1})", strImmediateTwoUp, strImmediateOneUp);
                    dt.Rows[row][col] = strSum;
                }
                else
                {
                    dt.Rows[row][col] = Convert.ToInt32(new Random().Next(1, NumRows));
                }
            }

        }

        startsum = 1;
    }
    return dt;
}

This routine generate excel file from my data table where problem lies that formula is not evaluating. 该例程从我的数据表生成excel文件,问题在于公式未求值。

public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
{
    int i = 0;
    int j = 0;
    int count = 0;
    ISheet sheet = null;
    IWorkbook workbook=null;
    double d;

    string fileName = @"d:\SpreadsheetLight_npoi.xlsx";

    FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
    if (fileName.IndexOf(".xlsx") > 0) // 2007
        workbook = new XSSFWorkbook();
    else if (fileName.IndexOf(".xls") > 0) // 2003
        workbook = new HSSFWorkbook();

    try
    {
        if (workbook != null)
        {
            sheet = workbook.CreateSheet(sheetName);
        }
        else
        {
            return -1;
        }

        if (isColumnWritten == true)
        {
            IRow row = sheet.CreateRow(0);
            for (j = 0; j < data.Columns.Count; ++j)
            {
                row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
            }
            count = 1;
        }
        else
        {
            count = 0;
        }

        for (i = 0; i < data.Rows.Count; ++i)
        {
            IRow row = sheet.CreateRow(count);
            for (j = 0; j < data.Columns.Count; ++j)
            {
                if (Double.TryParse(data.Rows[i][j].ToString(), out d))
                {
                    row.CreateCell(j).SetCellValue(d);
                    //row.CreateCell(j).CellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00");
                }
                else
                {
                    row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString().Replace("=",string.Empty));
                    //row.CreateCell(j).SetCellFormula(data.Rows[i][j].ToString().Replace("=",string.Empty));
                }

            }
            ++count;
        }

        if (workbook is XSSFWorkbook)
        {
            XSSFFormulaEvaluator.EvaluateAllFormulaCells(workbook);
        }
        else
        {
            HSSFFormulaEvaluator.EvaluateAllFormulaCells(workbook);
        }
        workbook.Write(fs);
        return count;
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception: " + ex.Message);
        return -1;
    }
}

I evaluate my formula this way but still does not work. 我以这种方式评估我的公式,但仍然无法正常工作。

if (workbook is XSSFWorkbook)
{
    XSSFFormulaEvaluator.EvaluateAllFormulaCells(workbook);
}
else
{
    HSSFFormulaEvaluator.EvaluateAllFormulaCells(workbook);
}

Please advise me what to add or alter in my code as a result formula should be evaluated and will show right value when i will open excel file. 请告知我要在代码中添加或更改的内容,因为应该评估结果公式,并在打开Excel文件时显示正确的值。 thanks 谢谢

I have solved my issue. 我已经解决了我的问题。 here is code rectified code. 这是代码更正的代码。

for (i = 0; i < data.Rows.Count; ++i)
{
    IRow row = sheet.CreateRow(count);
    for (j = 0; j < data.Columns.Count; ++j)
    {
    if (Double.TryParse(data.Rows[i][j].ToString(), out d))
    {
        row.CreateCell(j).SetCellValue(d);
    }
    else
    {
       ICell cell = row.CreateCell(j);
        cell.SetCellType(CellType.Formula);
        cell.SetCellFormula(data.Rows[i][j].ToString().Replace("=", string.Empty));
    }

    }
    ++count;
}

if (workbook is XSSFWorkbook)
{
    XSSFFormulaEvaluator.EvaluateAllFormulaCells(workbook);
}
else
{
    HSSFFormulaEvaluator.EvaluateAllFormulaCells(workbook);
}
workbook.Write(fs);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM