Set html in Comment in excel using Aspose.Cells - c#

I am working n exporting excel using Aspose.Cells. In that i need to show some HTML formatted comment in specific column. But when i set note in comment using HTML string then it automatically modify that HTML. I am usiing below code
Workbook workbook = GetExcelWorkbook<AuditLogExport>(auditLogExportData, templatePath);
CommentCollection comments = workbook.Worksheets[0].Comments;
for (int i = 0; i < exportData.Count; i++)
{
if (exportData[i].IsDetailedChange)
{
int commentIndex = comments.Add(string.Format("E{0}", (i + 2)));
Aspose.Cells.Comment comment = comments[commentIndex];
**comment.HtmlNote = GetAuditLogCommentNote(exportData[i]);**
comment.WidthCM = 8.0;
comment.HeightCM = 20.0;
}
}
public static string GetAuditLogCommentNote(AuditLog auditLog)
{
string note = string.Empty;
note = "<table width='400px' style='border:solid 1px black'><tr><th>Changed Field</th><th>Previous</th><th>Current</th></tr>";
foreach (var history in auditLog.DetailChanges)
{
note += string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>", history.FieldName, history.FirstChange, history.LastChange);
}
note += "</table>";
return note;
}
When i am assigning value to HtmlNote property of comment it automatically change html with font tags and strip all table tags from string. Can someone please help on this?

Update-1
Well, we think, your requirement is not achievable using Microsoft Excel. If something is not possible with Microsoft Excel, then it will also not be possible with Aspose.Cells or any other API automatically.
Please see the following screenshot. It shows how your HTML looks like when it is viewed in Web Browser and when it is copied/pasted to Excel comment.
If you think, your requirement is doable using Microsoft Excel, please provide us your sample Excel file that you have created manually using Microsoft Excel. We will check it and investigate this issue further.
Update-2
We tested this issue with the following code and found that if we try to create comment with HtmlNote property, it does not work.
We have logged this issue in our database for investigation and for a fix. Once, the issue is resolved, we will update you in this post.
This issue has been logged as
CELLSNET-46210 - Creating Comment using HtmlNote property does not work
C#
Workbook wb = new Workbook();
Worksheet ws = wb.Worksheets[0];
int idx = ws.Comments.Add("E4");
Comment cm = ws.Comments[idx];
//cm.HtmlNote = "<Font Style=\"FONT-WEIGHT: bold;FONT-FAMILY: Tahoma;FONT-SIZE: 9pt;COLOR: #000000;TEXT-ALIGN: left;\">Heading: </Font><Font Style=\"FONT-FAMILY: Tahoma;FONT-SIZE: 9pt;COLOR: #000000;TEXT-ALIGN: left;\">This is some para. </Font><Font Style=\"FONT-WEIGHT: bold;FONT-FAMILY: Tahoma;FONT-SIZE: 9pt;COLOR: #000000;TEXT-ALIGN: left;\">Heading2:</Font><Font Style=\"FONT-FAMILY: Tahoma;FONT-SIZE: 9pt;COLOR: #000000;TEXT-ALIGN: left;\"> This is some para2.</Font>";
cm.HtmlNote = new Workbook("input.xlsx").Worksheets[0].Comments[0].HtmlNote;
cm.IsVisible = true;
wb.Save("output.xlsx");
Update-3
Your issue logged as CELLSNET-46210 has been fixed in Aspose.Cells for .NET v18.7. Please download it from this link.
https://www.nuget.org/packages/Aspose.Cells/18.7.0
Note: I am working as Developer Advocate at Aspose

Related

How to write data to an existing Excel doc in C#

I have a document that I need to update on a monthly basis and I'm writing an automation to do so. This is my first time attempting to update a document with C# as opposed to simply creating a new one. I have researched and tried implementing a few libraries that I've found online and here on StackOverflow, for example, ClosedXML, but so far I've had no luck. I understand this question has been asked here before, so my actual question is: Is my implementation incorrect/am I doing something wrong?
public void WriteToReport(List<BrandData> brandData, string reportFilePath)
{
using (var workbook = new XLWorkbook(reportFilePath))
{
var worksheet = workbook(1);
worksheet.Cell(26, 2).Value = "Hello World!";
workbook.SaveAs(reportFilePath);
}
}
Above is how I've tried to test ClosedXML so far. The GitHub docs imply that it should be this simple, but I don't see any changes made to the doc when the automation is finished. I've also tried using Streamwriter. If anyone can help me with ClosedXML or suggest another library that worked for them, it would be greatly appreciated.
Edit: Following explanations on other similar questions on here, I have tried this:
public void WriteToReport(List<BrandData> brandData, string reportFilePath)
{
var workbook = new XLWorkbook(reportFilePath);
var worksheet = workbook.Worksheet(1);
int numberOfLastColumn =
worksheet.LastColumnUsed().ColumnNumber();
IXLCell newCell = worksheet.Cell(numberOfLastColumn + 1, 1);
newCell.SetValue("Hello World");
workbook.SaveAs(reportFilePath);
}
Here is a simple example to write a string value to the first WorkSheet.
public void WriteToCell(string fileName, int row, int col, string value)
{
using var workbook = new XLWorkbook(fileName);
var worksheet = workbook.Worksheets.Worksheet(1);
worksheet.Cell(row, col).Value = value;
workbook.SaveAs(fileName);
}

Adding fields side by side in word footnote

Hi I am having an issue with my word application. I am trying to add a field side by side in the footnotes. The issue I am having is a merge conflict and I think this is because the range is the same and over writhing the other field. I am trying add them side by side in one line based on the end point of the previous field.
I have tried collapsing the range to the end but I can't get this to work. Any help would be much appreciated as I am newish to using the VSTO tools and tbh I find them not very good.
public static void insertHtmlIntoFootnoteResult (Field field, List<ct>
list)
{
for(var c in ct){
//I am trying to go to the end here
field.Result.Collapse(WdCollapseDirection.wdCollapseEnd);
//How do I create a new field and insert it here based of the the
//last fields ending position?
string guid = Guid.NewGuid().ToString();
var filename = Path.GetTempPath() + "temp" + guid + ".html";
using (StreamWriter s = File.CreateText(filename))
{
s.Write("I am test");
s.Close();
}
field.Result.InsertFile(filename);
File.Delete(filename);
}
} // _insertHtmlIntoRange
Hey so I found an answer eventually using the blog post by flowers
https://gist.github.com/FlorianWolters/6257233
Done by changing the insertempty() method to insert a Word.WdFieldType.wdFieldIf field.
Hope this helps for futre people!

Hyperlink to a cell on another workbook - EPPlus

I want to add an hyperlink to a cell of another workbook. I am able to refer the whole file but I have issues when referring an specific cell.
The generated hyperlink is well formed because when I click on modify hyperlink and then OK (without modifying it) on the generated Excel file then the hyperlink starts to work.
I have already tried with all the constructors of Uri, I tried to calculate the cell value but I don't find the solution. Here's my code.
This works:
resultSheet.Cells[currentRow, 10].Hyperlink = new Uri(message.myReference.filePath, UriKind.Absolute);
This doesn't work until clicking on modify and then ok on the generated Excel file.
resultSheet.Cells[currentRow, 10].Hyperlink = new Uri(message.myReference.filePath + "#'" + message.myReference.sheetName + "'!" + "A" + message.myReference.cellRow, UriKind.Absolute);
I would really appreciate any kind of help because I'm kinda stuck on this silly issue.
I've tried using the Interop library and this works for me.
Maybe you can use a similar sort of logic or idea.
Range whereHyperLinkWillBe = activeWorksheet.get_Range("O3", Type.Missing);
string filePathOfHyerlinkDestination = "C:\\Users\\Desktop\\HyerlinkFile.xlsx";
string hyperlinkTargetAddress = "Sheet1!B4";
activeWorksheet.Hyperlinks.Add(whereHyperLinkWillBe, filePathOfHyerlinkDestination ,hyperlinkTargetAddress, "Hyperlink Sample", "Hyperlink Title");
The official method is to use new ExcelHyperLink(), see
ws.Cells["K13"].Hyperlink = new ExcelHyperLink("Statistics!A1", "Statistics");
https://github.com/JanKallman/EPPlus/wiki/Formatting-and-styling
So I found the answer, I was able to do it by using the formula attribute of the cell as follow by adding the hyperlink reference and the value that I wanted to show on the cell:
resultSheet.Cells[currentRow, 10].Formula = "HYPERLINK(\"" + filePath + "#'" + sheetName + "'!" + rowLetter + rowNumber + "\",\"" + "message to show on the cell" + "\")";
resultSheet.Cells[currentRow, 10].Calculate();

How to allow user to edit ranges in Protected Excel using EPPlus and c#?

I am exporting protected excel sheet using EPPlus in my winform(C#) project. Now I want functionality to allow user to edit ranges in that protected excel sheet using same plugin.
It would be great if you provide Code snippet.
Thanks in advance.
var fileName = "sample.xlsx";
var fileInfo = new FileInfo(fileName);
using (var excel = new ExcelPackage(fileInfo))
{
var ws = excel.Workbook.Worksheets.Add("sheet1");
ws.Protection.IsProtected = true;
ws.ProtectedRanges.Add("editable", new ExcelAddress("C:N"));
excel.Save();
}
I know its very late to reply but may help others. I had a similar issue and was struggling to get sorting and auto-filtering in protected worksheet.
After protecting the worksheet, I have added below two settings that allow sorting and auto-filtering.
ws.Protection.IsProtected = True
ws.Protection.AllowSort = True
ws.Protection.AllowAutoFilter = True
In my case however the next requirement was to unlock some columns to allow editing, I achieved that using:
ws.Column(12).Style.Locked = False
If you have a range however you can try something like this:
For Each cell In ws.Cells("B1:C8")
cell.Style.Locked = False
Next

Clear Crystal Report Parameter

Using Visual Studio 2010 and Crystal Reports 13.0.
For the report, there is a prompt for the user to input a value. Then the report is generated with no problems.
If the user leaves the report.aspx page and comes back to run another report, the prompt does not show and the last report run is still there with the original value from the user.
Searching around for a solution, the only two found did not work:
//After the report loads
CrystalReportSource1.ReportDocument.ParameterFields.Clear();
Error:
You cannot add, remove or modify parameter fields using this method. Please modify the report directly.
Modify the report directly:
Right click the body of your Crystal Report
then goto:
Design -> Default Settings.. ->Reporting
Check the checkbox
Discard Saved Data When Loading Reports.
This did not work. The previous report still populates.
So, I now ask for a little insight on how to fix this problem.
As always, any suggestions are welcome.
Thanks
EDIT:
Here is the code behind for the report page. Many reports use this page....
CrystalReportSource1.Report.FileName = "reports\\" + fileName + ".rpt";
//CrystalReportSource1.Report.Parameters.Clear();
//CrystalReportSource1.Report = null;
//CrystalReportSource1.Report.Refresh();
if (!string.IsNullOrEmpty(Request.QueryString["item"]))
{
String Item = Request.QueryString["item"];
CrystalDecisions.Web.Parameter temp = new CrystalDecisions.Web.Parameter();
temp.Name = "Item";
temp.DefaultValue = Item;
CrystalReportSource1.Report.Parameters.Add(temp);
}
SqlConnectionStringBuilder settings = new SqlConnectionStringBuilder(MyConnectionString);
_crReportDocument = CrystalReportSource1.ReportDocument;
_crConnectionInfo.ServerName = settings.DataSource;
_crConnectionInfo.DatabaseName = settings.InitialCatalog;
_crConnectionInfo.UserID = settings.UserID;
_crConnectionInfo.Password = settings.Password;
//Get the table information from the report
_crDatabase = _crReportDocument.Database;
_crTables = _crDatabase.Tables;
//Loop through all tables in the report and apply the
//connection information for each table.
for (int i = 0; i < _crTables.Count; i++)
{
_crTable = _crTables[i];
_crTableLogOnInfo = _crTable.LogOnInfo;
_crTableLogOnInfo.ConnectionInfo = _crConnectionInfo;
_crTable.ApplyLogOnInfo(_crTableLogOnInfo);
}
You can try using this in your Page_Unload event.
Report.Close();
Report.Dispose();
That should get rid of the report when the page is unloaded and you will start fresh when the user comes back to the page.
There is a good example in this post here.
I found the solution!!!! -------- NOT
Add this line before all the code in my question above:
CrystalReportViewer1.ParameterFieldInfo.Clear();
Then load the file name and so forth.......

Categories