用NPOI生成包含富文本字符串(Rich Text String)的单元格

作者: Ken Yang

 

NPOI允许用户生成包含有富文本字符串的单元格。换句话说,你可以为同一个单元格内的字符串的不同部分设置不同的字体、颜色、下划线等等。

 

Imports System.IO
Imports NPOI.HSSF.UserModel
Imports NPOI.HPSF
Imports NPOI.HSSF.Util
Imports NPOI.POIFS.FileSystem
Imports NPOI.SS.UserModel

Module Module1

    Sub Main()
        Dim workbook As HSSFWorkbook = New HSSFWorkbook()

        Dim dsi As DocumentSummaryInformation = PropertySetFactory.CreateDocumentSummaryInformation
        dsi.Company = "Company Name"
        Dim si As SummaryInformation = PropertySetFactory.CreateSummaryInformation
        si.Author = "Ken Yang"
        si.Subject = "Generating Rich Text String using NPOI"
        Workbook.DocumentSummaryInformation = dsi
        Workbook.SummaryInformation = si

        Dim ws As Sheet = workbook.CreateSheet("sheet1")

        Dim r1 As Row = ws.CreateRow(0)
        Dim a1 As Cell = r1.CreateCell(0)

        ws.SetColumnWidth(0, 4000)
        r1.HeightInPoints = 51

        Dim style = workbook.CreateCellStyle()
        style.WrapText = True
        a1.CellStyle = style
        '设置富文本字符串
         Dim rts As HSSFRichTextString = New HSSFRichTextString("Red String." + vbLf + "Bold Text" + vbLf + "Strikeout Text" + vbLf + "Normal Text")

        '设置红色字体
         Dim redFont As HSSFFont = workbook.CreateFont()
        redFont.Color = HSSFColor.RED.index
        '设置粗体
         Dim boldFont As HSSFFont = workbook.CreateFont
        boldFont.Boldweight = 700
        '设置删除线
         Dim strikeoutFont As HSSFFont = workbook.CreateFont()
        strikeoutFont.IsStrikeout = True
        '设置富文本字符串的字体
         rts.ApplyFont(0, 11, redFont)
        rts.ApplyFont(12, 21, boldFont)
        rts.ApplyFont(22, 36, strikeoutFont)
        '将富文本字符串赋给A1单元格
         a1.SetCellValue(rts)

        Dim file As FileStream = New FileStream("e:\text.xls", FileMode.Create)

        workbook.Write(file)

    End Sub

End Module

 

 

效果截图:

image

 

posted @ 2012-05-28 18:07  Ken Yang  阅读(3132)  评论(0编辑  收藏  举报