简体   繁体   English

C#Excel.Range使用HTML数据设置单元格值

[英]C# Excel.Range Set a cell Value with HTML data

I need to find a way to set the excel cell value with html and have it display with the correct formatting. 我需要找到一种方法来用html设置excel单元格值,并用正确的格式显示它。 We load data from our database that sometimes contains html data with text mark up or html borders. 我们从数据库中加载有时包含带有文本标记或html边框的html数据的数据。 So I need to be able to tell excel that it is html data to render or convert the html to excel mark up or strip the html mark up, but that is not ideal. 因此,我需要能够告诉excel它是呈现或转换为excel标记或剥离html标记的html数据,但这并不理想。

var range = (Excel.Range)worksheet.Cells[rowIndex, columnIndex];
range.Value = "<b>This is <i>html text</i></b> that <font>could contain</font> any type of html;<br/>";

I do not have enought reputation to post this as a comment but here it goes: Take a close look at HTML Text with tags to formatted text in an Excel cell There is a solution in VBA that works and it can be translated into c# with a little bit of effort :) 我没有足够的声誉来发表此评论,但确实如此:仔细看HTML文本,在Excel单元格中使用带有标记的格式化文本标签 VBA中有一个解决方案可以工作,并且可以将其翻译为c#。一点努力:)

static void Main(string[] args)
    {
        object misValue = System.Reflection.Missing.Value;
        Type excelApplication = Type.GetTypeFromProgID("Excel.Application");
        dynamic excel = Activator.CreateInstance(excelApplication);
        dynamic xlWorkBook = excel.Workbooks.Add(misValue);
        dynamic SourceSheets = xlWorkBook.Worksheets[1];

        Type IeType = Type.GetTypeFromProgID("InternetExplorer.Application");
        dynamic Ie = Activator.CreateInstance(IeType);
        SourceSheets.Range("A1").Value = "<b>This is <i>html text</i></b> that <font>could contain</font> any type of html;<br/>";
        Ie.Visible = false;
        Ie.Navigate("about:blank");
        Ie.document.body.InnerHTML = SourceSheets.Range("A1").Value;
        Ie.document.body.createtextrange.execCommand("Copy");
        SourceSheets.Paste(SourceSheets.Range("A1"));
        Ie.Quit();
        xlWorkBook.SaveAs("test1", misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
    }

this is really a basic translation. 这确实是一个基本的翻译。 You have to save/dispose your object properly after but it works for what you are trying to do. 之后,您必须正确保存/处置对象,但是它可以满足您的尝试。 I just notice while trying the "allow access" of the internet explorer for the copy/paste bin but i am sure there is a work arround for that. 我只是在尝试尝试Internet Explorer的“允许/访问”复制/粘贴框时注意到,但是我敢肯定有一项工作可以解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM