[C#] NPOI Excel合併儲存格
2014-05-22
在.net 系統開發下,要處理Excel 通常會用 NPOI ,之前也有寫過文章
可參考: http://no2don.blogspot.com/2013/02/c-nopi-excel-xls.html
今天遇到的問題是,我要如何合併儲存格呢?
合併儲存格最重要的Code :
var workbook = new HSSFWorkbook();var sheetReportResult = workbook.CreateSheet("報表結果"); //產生第一個要用CreateRow sheetReportResult.CreateRow(0).CreateCell(0).SetCellValue("客戶資料");//建立跨越五列(共六列 1~6) ,跨越三欄(共四欄 A~D)sheetReportResult.AddMergedRegion(new CellRangeAddress(0, 5, 0, 3));重點在最後一行進行合併
合併後,塞資料方法一如往常,只是請注意,已經跨越的攔或列都必須要計算進去
完整Code :
protected void Button1_Click(object sender, EventArgs e)
{ var workbook = new HSSFWorkbook(); var sheetReportResult = workbook.CreateSheet("報表結果"); //產生第一個要用CreateRow sheetReportResult.CreateRow(0).CreateCell(0).SetCellValue("客戶資料"); //建立跨越五列(共六列 1~6) ,跨越三欄(共四欄 A~D) sheetReportResult.AddMergedRegion(new CellRangeAddress(0, 5, 0, 3)); //因為前6格(0~5)都被用掉了要從6開始 sheetReportResult.CreateRow(6).CreateCell(0).SetCellValue("姓名"); sheetReportResult.GetRow(6).CreateCell(1).SetCellValue("電話"); sheetReportResult.GetRow(6).CreateCell(2).SetCellValue("備註"); //第一Row 已經被Title用掉了 所以從1開始 for (var i = 7; i <= 20; i++) { sheetReportResult.CreateRow(i).CreateCell(0).SetCellValue("用戶" + i); sheetReportResult.GetRow(i).CreateCell(1).SetCellValue("091234567" + i); sheetReportResult.GetRow(i).CreateCell(2).SetCellValue("我是備註" + i);}
sheetReportResult.SetColumnWidth(0, 20 * 256);
sheetReportResult.SetColumnWidth(1, 40 * 256);
sheetReportResult.SetColumnWidth(2, 40 * 256);
//儲存到sample.xlsvar file = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "sample.xls", FileMode.Create);
workbook.Write(file);
file.Close();
}
範例下載:
