Set Text Length of Cell using ClosedXML - c#

I was wondering how do you set the text length of a cell in an Excel worksheet using ClosedXML. I have the suspicion that XLTextLengthCriteria may be helpful. I read the docs of ClosedXML but I did not find a concrete answer. Any help will be appreaciated.

For validation you can set the text length like this:
worksheet.Cell(1,1).SetDataValidation().TextLength.EqualOrLessThan(10);
For a complete column use this:
worksheet.Column(1).AsRange().SetDataValidation().TextLength.EqualOrLessThan(10);

check this solution
notice that ErrorStyle and ErrorTitle are optional
worksheet.Range("A1", "A1").SetDataValidation().TextLength.EqualOrGreaterThan(5);
worksheet.Range("A1", "A1").SetDataValidation().ErrorStyle = ClosedXML.Excel.XLErrorStyle.Stop;
//XLErrorStyle.Stop will prevent adding data,
//XLErrorStyle.Information will show hint,
//XLErrorStyle.Warning will let user choose to continue or not
worksheet.Range("A1", "A1").SetDataValidation().ErrorTitle = "Text Length should be greater than 4 charachters";

Related

C# - Read MergedCells range in EPPlus

How to read the value of range that is Merged with EPPlus?
Lets say the range "G15:G18" is merged. How do I retrieve the text inside that range?
I've tried this, but without success:
string txt = ws.Cells["G15:G18"].Value.ToString();
Thanks.
Looking better at the issue, I finally understood that what I was doing was actually bringing a collection of results, where only the first item has a value.
So, basically, this code:
string txt = ws.Cells["G15:G18"].Value.ToString();
would return an array like with the text for all the cells in the range.
But except for the first cell in the array, all cells are empty. Only the first cell hold the Value for the whole range.
What I did is as simple as this:
string val = ws.Cells["G15:G18"].First().Value.ToString();
It worked fine.
Unless I missed the boat, I think it might be even easier than you think... just look for the value for the first cell in the range:
string txt = ws.Cells["G15"].Value.ToString();
Also, if you know it's text or just want the text representation of the cell, you can use the Text property:
string txt = ws.Cells["G15"].Text;
I think this concept transcends EPPlus also -- you can reference it in Excel formulas, and I believe it works this way in Interop as well.

Write to Excel very large numeric value

I am trying to write to Excel using Excel Interop. One of my column will have a very numeric value (44 digits).
After checking similar posts in the internet, I tried setting the NumberFormat.
worksheet.Cells[i, j].NumberFormat = "#"; and worksheet.Cells[i, j].NumberFormat = "#";
But it still shows the values in format- ######... so on.. I tried expanding the columns too but that did not work. However, this worked for some of my other column where I have numeric values in 14 digits.
Any help? Please let me know if I can provide more details.
There is a 15 digit limit in Excel unfortunately
for cells use cells["A:A"].numberFormat = "#";
for columns use cells[0, 2].EntireColumn.NumberFormat = "#";
If showing the data in text is ok , then set the cell format to TEXT.

How to get cell value with applied formatting (formatted cell value) with OpenXML SDK

I've been googling and searching on the site for the answer, but I couldn't find a solution - everywhere people mostly discuss how to add new number format to the document and apply it.
What I need is to get the cell value as a string with applied formatting - i.e. same string as would be displayed by Excel.
I already figured that there's no easy way or built-in function which would return the readymade formatted value for a cell.
So it seems to me that to get the value I need to do two things:
1. Get the format string.
2. Format the cell value using this string.
But I have problems with both steps.
One can easily get CellFormat instance which would contain NumberFormatId:
CellFormat cellFormat = (CellFormat) document.WorkbookPart.WorkbookStylesPart.Stylesheet.CellFormats.ElementAt(cell.StyleIndex);
But how to get the format string with this NumberFormatId, if the id corresponds to one of standard predefined formats? (i.e. is below 160) They are not in the spreadsheet document and I can't believe that they should be hardcoded in the application.
Also, once the format string is somehow obtained, how to apply it to the cell value? So far I understand, the code should check the type of the cell value and if is Number - convert it to string using the format string.
I found this page which mentions using Microsoft.Office.Excel.Interop, but I would prefer to stay with OpenXML SDK only.
Overall, I'm very surprised that it's so difficult to find a definitive answer to this question on the Web as I thought that this would be something which many developers need in their daily work.
Men, this is a hard one... I will be adding here things that i found that could be worth..
First is to get the numbering format of the cell (once you have the CellFormat:
string format = excel.WorkbookPart.WorkbookStylesPart.Stylesheet.NumberingFormats.Elements<NumberingFormat>()
.Where(i => i.NumberFormatId.ToString() == cellFormat.NumberFormatId.ToString())
.First().FormatCode;
For more information about this you can go to: NumberingFormats
Im trying to find out how to apply this format to the cell.CellValue property... I think thats the way you have to go!
Ok, reading the ClosedXml code (its open source), seems to be easy to get the format.
Simply convert the value text to its type (int, double, etc) and call the ToString method passing the format. I was trying do that with the String.Format and didnt work. Ive tested the ToString and it works, but something still missing.
I recommend to you to look at this class and get the code from the method GetFormattedString() as #El G tell in his comment.
Bassicaly you will have to add something like this:
double d = double.Parse(cell.CellValue.InnerText);
string val = d.ToString(format);
Hope it helps you...
If you want to take cell value with applied formatting, same as displayed in Excel, use .Text property of Cell object. Like this:
String formattedValue = cell.Text

How to append Values to Excel Range

I have an Excel workbook which has 3 worksheets with a named range defined for address A1:F10 in each sheet and have some values.
I wanted to have a range defined and set all the 3 worksheet range values to this.
Example
TempRange = Test1Range + Test2Range + Test3Range
Any help would be appreciated
IF all four ranges are the same size, then you can add 'em up with an array formula. Select the entire area of "TempRange", and type
=Test1Range + Test2Range + Test3Range
... and then, to enter it, hit CTRL+SHIFT+ENTER, not plain ENTER.
It's been a long time, and I use OpenOffice these days, so I might have details wrong. The general idea works, though, so even if this exact thing isn't right, googling for "Excel array formula" will probably turn up some helpful information.
I found the answer
Application.Union(Range1,Range2)

NPOI create cell containing bold and non bold text

I'm using NPOI to output excel from Asp.Net MVC app and works very well with plain text but have now been requested to add formatting and am having problems where I need to have a single cell with bold text followed by non-bold text. e.g.
This text bold - this text normal
I know I can give a cell a single style but this won't help and I cannot see anyway to give a cell some pre-formatted rich text.
The only possible solution that I can think of is creating two cells separately and the merge them together but will that then mean the formatting will be lost?
Is there a way to do this that I have missed in NPOI?
You may try this:
var font = reportWorkbook.CreateFont();
font.FontHeightInPoints = 11;
font.FontName = "Calibri";
font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.BOLD;
var cell = headerRow.CreateCell(0);
cell.SetCellValue("Test Bold");
cell.CellStyle = reportWorkbook.CreateCellStyle();
cell.CellStyle.SetFont(font);
Fortunately, you able to do that... Look at this code:
Font f1=wb.CreateFont();
f1.Color=HSSFColor.RED.index;
ws.GetRow(1).GetCell(0).RichStringCellValue.ApplyFont(1, 5, f1);
Seems that the Ernie Banzon answer no longer works exactly as described, possibly due to a namespace change (or in fact that I'm using the HSSF namespace?)
// usings
using NPOI.HSSF.UserModel;
// IWorkbook doc
IFont font = doc.CreateFont();
font.FontHeightInPoints = 11;
font.FontName = "Arial";
font.Boldweight = (short)FontBoldWeight.BOLD;
Use this option
font.Boldweight = (short)700;//FontBoldWeight.Bold;
Actual syntax should be like below. But both of these syntax doesn't works sometime
font.Boldweight = FontBoldWeight.Bold ;
Or
font.Boldweight = (short)FontBoldWeight.Bold;
FontBoldWeight is type enum, which after type casting may not work sometime. As a workaround if you type caste or use actual short value of enum directly, it works. Below is the declaration of FontBoldWeight. it will make things clear.
**public enum FontBoldWeight
{
None = 0,
Normal = 400,
Bold = 700,
}**
After a fair amount of investigation it seems that you are not able to do this inside of NPOI as it doesn't provide the necessary functionality to allow you to set formatting on specific text within a cell like I was attempting to do.

Categories

Resources