for (var i = 1; i <= 20; i++)
{
sheetReportResult.CreateRow(i).CreateCell(0).SetCellValue("用戶" + i);
if (i== 5)
{
var cell = sheetReportResult.GetRow(i).CreateCell(1);
cell.CellStyle = styleR;
cell.SetCellValue("091234567" + i);
}
else if (i == 10)
{
var cell = sheetReportResult.GetRow(i).CreateCell(1);
cell.CellStyle = styleG;
cell.SetCellValue("091234567" + i);
}
else {
var cell = sheetReportResult.GetRow(i).CreateCell(1);
cell.SetCellValue("091234567" + i);
}
sheetReportResult.GetRow(i).CreateCell(2).SetCellValue("我是備註" + i);
}
結果:
完整程式碼:
var workbook = new HSSFWorkbook();
var sheetReportResult = workbook.CreateSheet("報表結果");
//綠色的Style
NPOI.SS.UserModel.IFont fontG = workbook.CreateFont();
fontG.Color = NPOI.SS.UserModel.IndexedColors.Green.Index;
var styleG = workbook.CreateCellStyle();
styleG.SetFont(fontG);
//紅色的Style
NPOI.SS.UserModel.IFont fontR = workbook.CreateFont();
fontR.Color = NPOI.SS.UserModel.IndexedColors.Red.Index;
var styleR = workbook.CreateCellStyle();
styleR.SetFont(fontR);
//產生第一個要用CreateRow
sheetReportResult.CreateRow(0).CreateCell(0).SetCellValue("姓名");
//之後的用GetRow 取得在CreateCell
sheetReportResult.GetRow(0).CreateCell(1).SetCellValue("電話");
sheetReportResult.GetRow(0).CreateCell(2).SetCellValue("備註");
//第一Row 已經被Title用掉了 所以從1開始
for (var i = 1; i <= 20; i++)
{
sheetReportResult.CreateRow(i).CreateCell(0).SetCellValue("用戶" + i);
if (i== 5)
{
var cell = sheetReportResult.GetRow(i).CreateCell(1);
cell.CellStyle = styleR;
cell.SetCellValue("091234567" + i);
}
else if (i == 10)
{
var cell = sheetReportResult.GetRow(i).CreateCell(1);
cell.CellStyle = styleG;
cell.SetCellValue("091234567" + i);
}
else {
var cell = sheetReportResult.GetRow(i).CreateCell(1);
cell.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);
var file = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "sample.xls", FileMode.Create);
workbook.Write(file);
file.Close();
--
Before you read this, the article was in a superposition of human and AI. Upon observation, the wave function collapsed into a sleep-deprived developer.