npoi icon indicating copy to clipboard operation
npoi copied to clipboard

ExcelToHtmlConverter.ProcessWorkbook throws Illegal IndexedColor index: 0 error on .NET Core 3.1

Open Evanyi0016 opened this issue 3 years ago • 6 comments

以下代码在.net framework中可顺利执行,但在core 3.1下2.5.4版本报错:Illegal IndexedColor index: 0;

` ///

/// (NPOI)Excel转HTML /// /// HTML文件的的名称(不带后缀) /// 需要转换Excel的绝对路径 /// public string ExcelToHtml(string Filename) { IWorkbook workbook; //获取后缀名称 string fileExt = Path.GetExtension(Filename).ToLower(); //判断是否可以打开该文件,如果出错则文件已经打开或者有异常 try { System.IO.FileStream stream = System.IO.File.OpenWrite(Filename); stream.Close(); } catch { return null; } using (FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.Read)) { //如果是XLSX格式选择XSSFWorkbook ,如果是XLS格式选择HSSFWorkbook if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; } if (workbook == null) { return null; } }

        ExcelToHtmlConverter eth = new ExcelToHtmlConverter();

        // 设置输出参数
        eth.OutputColumnHeaders = true; //是否输出ColumnHeader
        eth.OutputHiddenColumns = false;//是否在表头插入一行序列号
        eth.OutputHiddenRows = false;//是否输出HiddenRow
        eth.OutputLeadingSpacesAsNonBreaking = true; //不清楚
        eth.OutputRowNumbers = false;//是否在列头插入一行序列号
        eth.UseDivsToSpan = false; //不清楚


        // 加载Excel文件
        eth.ProcessWorkbook(workbook); //***此处报错:Illegal IndexedColor index: 0****

        // 保存文件值当前路径
        return eth.Document.InnerXml;

      //  string htmlFile = Application.StartupPath + "\\" + HtmlName + ".html";
      //  eth.Document.Save(htmlFile);
      //   return htmlFile;

    }`

simple

以下是Excel样例。 simple.xlsx

Evanyi0016 avatar Aug 18 '21 10:08 Evanyi0016

Can you provide the Excel file?

tonyqus avatar Aug 18 '21 14:08 tonyqus

Can you provide the Excel file?

The sample has been uploaded.

Evanyi0016 avatar Aug 19 '21 00:08 Evanyi0016

The exception thrown by IndexedColor.ValueOf() method. In some cases, the color value=0. But there is no pre-defined color whose index equals 0.

tonyqus avatar Dec 12 '21 22:12 tonyqus

Hi,

Is there any way to avoid this exception?

isaacfi avatar Jan 12 '23 14:01 isaacfi

Here is a simple workaround :

(typeof(IndexedColors).GetField("mappingIndex", BindingFlags.Static | BindingFlags.NonPublic)
   .GetValue(null) as Dictionary<int, IndexedColors>)[0] = IndexedColors.Black;

But a real fix is still very welcome

PhenX avatar Feb 13 '23 10:02 PhenX

Thanks for the "fix", @PhenX. In my case I needed white instead of black, so it seems the color is not fixed, but you lead me on the right track. :)

quiian avatar Nov 06 '23 07:11 quiian