2017-10-13 197 views
1

我想在C#中使用NPOI Excel創建單元格註釋。我沒有找到任何明確的文件。我自己寫下如下。如何在C#中使用NPOI Excel添加單元格註釋?

NPOI.HSSF.Record.NoteRecord nr = new NPOI.HSSF.Record.NoteRecord(); 
nr.Author = "Some Author"; 
NPOI.HSSF.Record.TextObjectRecord tor = new NPOI.HSSF.Record.TextObjectRecord(); 
tor.Str = new HSSFRichTextString("something"); 

HSSFComment cm = new HSSFComment(nr, tor); 
cm.Visible = true; 

sheet.GetRow(i).Cells[k + 8].CellComment = cm; 

該代碼無法正常工作。我在生成的excel文件中看不到有關該單元格的任何評論。有沒有人知道我該如何在特定的單元格中添加評論?

回答

2

您需要使用繪圖族長創建單元格註釋。然後你可以定義你的作者和文本。您也可以應用一些字體自定義。

請試試這個代碼,我評論的不同步驟:

HSSFWorkbook workbook = new HSSFWorkbook(); 
HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("Sheet1"); 
HSSFRow row = (HSSFRow)sheet.CreateRow(0); 
HSSFCell cell = (HSSFCell)row.CreateCell(0); 
cell.SetCellValue("Cell1"); 

// Create the drawing patriarch (top level container for all shapes including cell comments) 
IDrawing patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch(); 

// Client anchor defines size and position of the comment in the worksheet 
IComment comment = patriarch.CreateCellComment(new HSSFClientAnchor(0, 0, 0, 0, 2, 1, 4, 4)); 

// Set comment author 
comment.Author = "Author"; 

// Set text in the comment 
comment.String = new HSSFRichTextString($"{comment.Author}:{Environment.NewLine}A comment"); 

// If you want the author displayed in bold on top like in Excel 
// The author will be displayed in the status bar when on mouse over the commented cell 
IFont font = workbook.CreateFont(); 
font.Boldweight = (short)FontBoldWeight.Bold; 
comment.String.ApplyFont(0, comment.Author.Length, font); 

// Set comment visible 
comment.Visible = true; 

// Assign comment to a cell 
cell.CellComment = comment; 

using (MemoryStream exportData = new MemoryStream()) 
{ 
    workbook.Write(exportData); 
    Response.ContentEncoding = Encoding.UTF8; 
    Response.Charset = Encoding.UTF8.EncodingName; 
    Response.ContentType = "application/vnd.ms-excel"; 
    Response.AddHeader("content-disposition", $"attachment; filename=test.xls"); 
    Response.Clear(); 
    Response.BinaryWrite(exportData.GetBuffer()); 
    Response.End(); 
} 

參考文獻:

+0

感謝krlzlx。我已經和族長一起處理了。 – aanilapaydin

+0

不客氣。總是樂於提供幫助。 – krlzlx

相關問題