asp.net-core - 如何获取 NPOI Excel RichStringCellValue?

标签 asp.net-core npoi

我正在使用 DotNetCore.NPOI (1.2.1) 来读取 MS Excel 文件。

一些单元格是文本类型并包含格式化字符串(例如一些粗​​体字)。

如何获取格式化的单元格值?我的最终目标:以 HTML 形式检索单元格文本。

我试过了

var cell = row.GetCell(1);
var richStringCellValue = cell.RichStringCellValue;

但这不会让我访问格式化字符串(只是没有格式的纯字符串)。

有人有想法或解决方案吗?

最佳答案

我认为在这种情况下你必须走更长的路线。首先,您必须维护单元格值的格式,例如日期、货币等,然后从单元格值中提取样式并将单元格值嵌入到该样式下。

最好的选择是编写扩展方法来获取格式和样式值。

要获取格式请参阅此链接 How to get the value of cell containing a date and keep the original formatting using NPOI

对于样式,首先您必须检查并找到运行文本的确切样式,然后返回 html 标记内的值,下面的方法将为您提供从单元格值中提取样式的想法。代码未经测试,您可能必须包含缺少的库。

 public void GetStyleOfCellValue()
        {

            XSSFWorkbook wb = new XSSFWorkbook("YourFile.xlsx");
            ISheet sheet = wb.GetSheetAt(0);
            ICell cell = sheet.GetRow(0).GetCell(0);  
            XSSFRichTextString richText = (XSSFRichTextString)cell.RichStringCellValue;
            int formattingRuns = cell.RichStringCellValue.NumFormattingRuns;

            for (int i = 0; i < formattingRuns; i++)
            {
                int startIdx = richText.GetIndexOfFormattingRun(i);
                int length = richText.GetLengthOfFormattingRun(i);
                Console.WriteLine("Text: " + richText.String.Substring(startIdx, startIdx + length));
                if (i == 0)
                {
                    short fontIndex = cell.CellStyle.FontIndex;
                    IFont font = wb.GetFontAt(fontIndex);
                    Console.WriteLine("Bold: " + (font.IsBold)); // return string <b>my string</b>.
                    Console.WriteLine("Italics: " + font.IsItalic + "\n"); // return string <i>my string</i>. 
                    Console.WriteLine("UnderLine: " + font.Underline + "\n"); // return string <u>my string</u>. 
                }
                else
                {
                    IFont fontFormat = richText.GetFontOfFormattingRun(i);
                    Console.WriteLine("Bold: " + (fontFormat.IsBold)); // return string <b>my string</b>.
                    Console.WriteLine("Italics: " + fontFormat.IsItalic + "\n");// return string <i>my string</i>. 
                }
            }
        }

关于asp.net-core - 如何获取 NPOI Excel RichStringCellValue?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52605284/

相关文章:

asp.net-core - 使用 VSTS 的 ASP.NET Core 2.1 CI/CD 构建错误

debugging - VS 2015 Update 2 - 调试时变量不存在,为什么?

c# - Entity Framework 返回的列表为空

c# - NPOI Excel 数字格式未显示在 asp.net 的 Excel 工作表中

c# - 我该如何将 NPOI.SS 转换为 NPOI.XSSF?

Startup.Configure 中的 ASP.NET Core 依赖注入(inject)

asp.net-core - 为什么删除迁移运行我的应用程序?

.net - 如何从 VB.Net 中的字典(字符串,对象)中重铸对象

c# - NPOI 日期格式单元格

c# - 使用 NPOI 编辑和保存 xlsx 会导致文件损坏