我不确定是否可以修复它,但我有以下情况:
我有一些DataTable
有一些数据,我需要准备使用这些数据的图表。我已经读过,在NPOI
中制作动态任何图表的唯一可能性是准备模板并仅填充excel的单元格。但我有一些问题:
我可以拥有动态数据行数。所以我需要能够使用一个模板,例如4行和7行。所以我有想法选择更多的数据(在模板中)并只使用其中的一部分但是我有这样的情况:
所以我需要动态改变图表范围。有可能解决我的问题吗?
答案 0 :(得分: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;
}
}
希望它会帮助某人:)