Excel动态合并行、合并列


背景:      

      在北京工作的时候,又一次同事问了我这样一个问题,说我要把从数据库获取到的数据直接通过NPOI进行导出,但是我对导出的格式要特殊的要求,如图:



冥思苦想,最终顺利帮同事解决问题,虽然有点瑕疵,但是毕竟是盲写,也算是圆满完成任务了:

//假设 DataTable dt=获取到的datatable
List<Year_Month> listYear=Year_Month.ToList();//年限list
List<Data> dataList=Data.ToList();//国别list
List<dt> dtList=dt.ToList();//数据list

int countYear=listYear.Count();//年限数量
int countdata=dataList.Count();//国别数量
int countdt=dtList.Count();//数据数量

row=sheet.CreateRow(0);//创建行
cell=row.CreateCell(0);//创建列
cell.SetCellValue("时间");//单元格赋值
//合并行,合并列
sheet.AddMergedRegion(new CellRangeAddress(0,2,0,0));//些数据头,时间

//标题进出口岸
cell=row.CreateCell(1);//创建列
cell.SetCellValue("进出口岸");//单元格赋值
//合并行,合并列
sheet.AddMergedRegion(new CellRangeAddress(0,0,1,countdata*2));//进出口岸

//进口口岸名称
row=sheet.CreateRow(1);
for(int i=0;i<dataList.count;i++)
{
	//根据数据条数,动态创建列
	cell=row.CreateCell(2*i+1);
	//合并行,合并列
	sheet.AddMergedRegion(new CellRangeAddress(1,1,2*i+1,2*(i+1)));//进出口岸
	//批量赋值
	cell.SetCellValue(dataList[i].GuoName);    
}

//进出口
row=sheet.CreateRow(2);
for(int i=0;i<dataList.count;i++)
{
	cell=row.CreateCell(2*i+1);
	cell.SetCellValue("进口");
    cell=row.CreateCell(2*i+2);   
    cell.SetCellValue("出口");	
}

//数据
for(int i=0;i<yearList.count;i++)
{
	row=sheet.CreateRow(i+3);//年份
    cell=row.CreateCell(0);	
	cell.SetCellValue(yearList[i].nian);
	
	//数据赋值
	for(int j=0;j<datalist.count;j++)
	{
		var item=shujuzongtiaoshu.where(u=>u.nianfen==yearList[i].year).toList();
		for(int k=0;k<item.count;k++)
		{
			//数据有值赋值,没有的值得赋空值单元格站位
			if(item[k].guobiemingcheng==dataList[j].name)
			{
				cell=row.CreateCell(2*j+1);
				cell.SetCellValue(datalist[j].jinkou);
				cell=row.CreateCell(2*j+2);
				cell.SetCellValue(datalist[j].chukou);
			}else
			{
				cell=row.CreateCell(2*j+1);
				cell.SetCellValue("");
				cell=row.CreateCell(2*j+2);
				cell.SetCellValue("");
			}
		}
	}	
}



效果:



提示:图片纯属后来补充,不能代表正式环境下生成文档格式,请见谅


总结:

        技术什么的只要肯下功夫都会有的,面包会有的,奶油也会有的。可是难能可贵的是我们在不知道怎么做的时候能坚持一下,去自己脑补,我们要对自己,对生活乃至对工作任务及实现方法充满幻想与想象,只有这样,我们才有取之不竭用之不尽的创新去支持我们,给自己加油!



posted @ 2016-07-24 15:51  Double-Eggs  阅读(625)  评论(0编辑  收藏  举报