1. 程式人生 > >Excel動態合併行、合併列

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("");
			}
		}
	}	
}

效果:


提示:圖片純屬後來補充,不能代表正式環境下生成文件格式,請見諒

總結:

        技術什麼的只要肯下功夫都會有的,麵包會有的,奶油也會有的。可是難能可貴的是我們在不知道怎麼做的時候能堅持一下,去自己腦補,我們要對自己,對生活乃至對工作任務及實現方法充滿幻想與想象,只有這樣,我們才有取之不竭用之不盡的創新去支援我們,給自己加油!