使用NPOI库在Excel中生成数据的甘特图的操作:
- 引用NPOI库的命名空间。
 
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
- 创建一个Excel工作簿:
 
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet2 = workbook.CreateSheet("甘特图");
// 设置甘特图的标题和列名
IRow headerRow = sheet2.CreateRow(0);
headerRow.CreateCell(0).SetCellValue("任务");
headerRow.CreateCell(1).SetCellValue("开始日期");
headerRow.CreateCell(2).SetCellValue("结束日期");
// 根据数据生成甘特图
for (int i = 0; i < dataItems.Count; i++)
{
    DataItem item = dataItems[i];
    IRow row = sheet2.CreateRow(i + 1);
    row.CreateCell(0).SetCellValue(item.Name);
    row.CreateCell(1).SetCellValue(item.StartDate.ToString());
    row.CreateCell(2).SetCellValue(item.EndDate.ToString());
    // 创建甘特图的起始日期和结束日期的单元格样式
    ICellStyle style = workbook.CreateCellStyle();
    style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.LightGreen.Index;
    style.FillPattern = FillPattern.SolidForeground;
    // 根据起始日期和结束日期设置甘特图的单元格样式
    int startColIndex = GetColumnIndexByDate(item.StartDate);
    int endColIndex = GetColumnIndexByDate(item.EndDate);
    for (int j = startColIndex; j <= endColIndex; j++)
    {
        ICell cell = row.CreateCell(j);
        cell.CellStyle = style;
    }
}
// 设置甘特图的列宽
for (int i = 0; i < 3; i++)
{
    sheet2.AutoSizeColumn(i);
}
- 保存Excel文件。
 
using (FileStream file = new FileStream("path/to/excel/file.xls", FileMode.Create, FileAccess.Write))
{
    workbook.Write(file);
}
示例假设已经从数据库中获取了数据,并将其存储在一个名为DataItem的自定义类中,请根据实际情况进行相应的调整。

本文暂时没有评论,来添加一个吧(●'◡'●)