使用C#

时间:2016-05-18 17:28:20

标签: c# excel hssfworkbook

我正在尝试使用HSSFWorkbook生成Excel工作表。我想设置一个单元格的背景颜色。我正在使用HSSFWorkbook,但遗憾的是无法获得背景颜色。

我需要将一些细胞设置为相同的颜色,将其他一些细胞设置为多种颜色。

我的代码到目前为止:

HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream memoryStream = new MemoryStream();
DataSet repds = exceldetils.ToDataSet("Batch");
HSSFSheet sheets = (NPOI.HSSF.UserModel.HSSFSheet)workbook.CreateSheet("Batch");
HSSFRow headerRow = (NPOI.HSSF.UserModel.HSSFRow)sheets.CreateRow(0);
//
List<string> columnnames = new List<string>();
foreach (DataColumn column in repds.Tables[0].Columns)
{
  //column.ColumnName = HSSFFont.FONT_ARIAL;
  // columnnames.Add(column.ColumnName);
  headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
}
var cHelp = workbook.GetCreationHelper();
HSSFFont hFont = (HSSFFont)workbook.CreateFont();

hFont.Boldweight = (short)FontBoldWeight.Bold;
hFont.Color = HSSFColor.Black.Index;
hFont.FontHeightInPoints = 10   ;
HSSFCellStyle hs = workbook.CreateCellStyle();
HSSFCellStyle hStyle =(HSSFCellStyle) workbook.CreateCellStyle(); 

hStyle.SetFont(hFont);
hStyle.BorderBottom = BorderStyle.Medium;
hStyle.FillBackgroundColor = HSSFColor.Black.Index;

hStyle.FillPattern = FillPattern.SolidForeground;
int cellCount = 0;
foreach (string str in columnnames)
{
  HSSFCell cell = (HSSFCell)headerRow.CreateCell(cellCount);
  cell.SetCellValue(cHelp.CreateRichTextString((str)));
  cell.CellStyle = hStyle;
  cellCount += 1;
}

int rowIndex = 1;
foreach (DataRow row1 in repds.Tables[0].Rows)
{
  HSSFRow dataRow = (NPOI.HSSF.UserModel.HSSFRow)sheets.CreateRow(rowIndex);
  foreach (DataColumn column in repds.Tables[0].Columns)
  {
    dataRow.CreateCell(column.Ordinal).SetCellValue(row1[column].ToString());
  }
  rowIndex++;
}
workbook.Write(memoryStream);
//memoryStream.Flush();
//memoryStream.GetBuffer();

0 个答案:

没有答案