当单元格值在 0.001 到 9.999(小数)范围内时,C# NPOI 将折线图绘制为 Excel

C# NPOI draw line chart to Excel when cell value on range 0.001 to 9.999 (fractional numbers)

当单元格值在 0.001 到 9.999(小数)范围内时,C# NPOI 将折线图绘制为 Excel

我可以在单元格值类似(0、1、2、... 9)或其他整数值时绘制图表,但当我尝试使用(0,293 或其他小数) 我看到错误:

"Removed part: /xl/drawings/drawing1.xml part. (Drawing figure)"
(当打开 Excel 文件时)。

我尝试在 google 和 github 中搜索解决方案,但没有找到类似的情况。 也许有人遇到过这个问题。

感谢您的帮助。

已更新 添加了报告文件 Good report Repot with error message

**为解释问题添加了代码:**

class Program
{
    const int NUM_OF_ROWS = 3;
    const int NUM_OF_COLUMNS = 10;

      static void CreateChart(IDrawing drawing, ISheet sheet, IClientAnchor anchor)
    {
        IChart chart = drawing.CreateChart(anchor);
        IChartLegend legend = chart.GetOrCreateLegend();
        legend.Position = LegendPosition.TopRight;

        ILineChartData<double, double> data = chart.ChartDataFactory.CreateLineChartData<double, double>();

        // Use a category axis for the bottom axis.
        IChartAxis bottomAxis = chart.ChartAxisFactory.CreateCategoryAxis(AxisPosition.Bottom);
        IValueAxis leftAxis = chart.ChartAxisFactory.CreateValueAxis(AxisPosition.Left);

        IChartDataSource<double> xs = DataSources.FromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1));
        IChartDataSource<double> ys1 = DataSources.FromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1));

        data.AddSeries(xs, ys1);

        chart.Plot(data, bottomAxis, leftAxis);
    }

    static void Main(string[] args)
    {
        IWorkbook wb = new XSSFWorkbook();
        ISheet sheet = wb.CreateSheet("linechart");

        // Create a row and put some cells in it. Rows are 0 based.
        IRow row;
        ICell cell;
        for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++)
        {
            row = sheet.CreateRow((short)rowIndex);
            for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++)
            {
                cell = row.CreateCell((short)colIndex);

                //This generate graph
                //cell.SetCellValue(colIndex * (rowIndex + 1));

                //This make error when open Excel file
                cell.SetCellValue(colIndex * (rowIndex + 1) + 0.1);
            }
        }

        IDrawing drawing = sheet.CreateDrawingPatriarch();
        IClientAnchor anchor1 = drawing.CreateAnchor(0, 0, 0, 0, 0, 5, 10, 8);
        CreateChart(drawing, sheet, anchor1);
        //Write to Excel file
        using (FileStream fs =File.Create("test1.xlsx"))
        {
            wb.Write(fs);
        }
    }
}

我找到了解决方案 - 并不完美,但很有效。

  1. 将单元格类型设置为字符串。
  2. 绘制图表(使用默认值(0),因为我们使用字符串单元格类型进行绘制)
  3. 将单元格类型更新为数字,然后图表将使用数字数据自动刷新。