1

我不确定是否可以修复它,但我有以下情况:

我有DataTable一些数据,我需要准备使用这些数据的图表。我已经读过动态制作任何图表的唯一可能性NPOI是准备模板并仅填充excel的单元格。但我有一些问题

我可以拥有动态数量的数据行。所以我需要能够使用一个模板来例如 4 和 7 行。所以我有想法选择更多数据(在模板中)并只使用其中的一部分,但后来我遇到了这样的情况:

所以我需要动态改变图表的范围。有没有可能解决我的问题?

4

1 回答 1

0

填充表格后,您只需更改图表中的范围。这是为三个图表填充表格的示例:

public static void ExportPackingReport_NPOI(string filepath, DataTable table)
        {
            IWorkbook xwb; // Workbook
            HSSFSheet sheet; // Sheet
            HSSFChart chart_0;// chart 1
            HSSFChart chart_1;// chart 2
            HSSFChart chart_2;// chart 3
            int rowIndex = 60; //First row of table with data
            int colIndex = 0;//First column of table with data
            int rows_count = table.Rows.Count; //Count of data in table
            try
            {
                //Read file
                using (FileStream rstr = new FileStream(filepath, FileMode.Open, FileAccess.Read))
                {
                    xwb = new HSSFWorkbook(rstr);
                    sheet = (HSSFSheet)xwb.GetSheet(xwb.GetSheetAt(0).SheetName);
                    var charts = HSSFChart.GetSheetCharts(sheet);
                    chart_0 = charts[0]; 
                    chart_1 = charts[1]; 
                    chart_2 = charts[2]; 
                    //Write file
                    using (FileStream wstr = new FileStream(filepath, FileMode.Open, FileAccess.ReadWrite))
                    {
                        //Populating file with data from Datatable
                        SetRowData_NPOI(table, xwb, rowIndex, colIndex);
                        //Overriding data ranges of charts 
                        CellRangeAddressBase chart_range_G = new CellRangeAddress(rowIndex + 1, rowIndex + rows_count, 6, 6);
                        CellRangeAddressBase chart_range_H = new CellRangeAddress(rowIndex + 1, rowIndex + rows_count, 7, 7);
                        CellRangeAddressBase chart_range_I = new CellRangeAddress(rowIndex + 1, rowIndex + rows_count, 8, 8);
                        CellRangeAddressBase chart_range_J = new CellRangeAddress(rowIndex + 1, rowIndex + rows_count, 9, 9);

                        //Apply new ranges of charts 
                        chart_0.Series[0].SetValuesCellRange(chart_range_G);
                        chart_0.Series[1].SetValuesCellRange(chart_range_J);

                        chart_1.Series[0].SetValuesCellRange(chart_range_H);
                        chart_1.Series[1].SetValuesCellRange(chart_range_J);

                        chart_2.Series[0].SetValuesCellRange(chart_range_I);
                        chart_2.Series[1].SetValuesCellRange(chart_range_J);

                        xwb.Write(wstr);
                        wstr.Close();

                    }
                    rstr.Close();
                    xwb.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

希望它会帮助某人:)

于 2016-11-23T16:02:35.103 回答