use the conditional format with epplus - c#

I´m trying to aplly a conditional format to a an Excel using eppplus, in that case i want to apply a pattern to all odd rows. so i try use the mod function, but not working, i don´t know how to put the formula
ExcelAddress _formatRangeAddress = new ExcelAddress("A2:Q" + (listSize+ 1));
string _statement = "MOD(ROW();2)=0";
var _cond1 = hoja.ConditionalFormatting.AddExpression(_formatRangeAddress);
_cond1.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
_cond1.Style.Fill.BackgroundColor.Color = System.Drawing.Color.Gray;
_cond1.Formula = _statement;

Check the formula string. I think you want a , instead of that ;. So change this:
string _statement = "MOD(ROW();2)=0";
to this:
string _statement = "MOD(ROW(),2)=0";

Related

How should we reverse format & extract a string in C#?

Pretty sure we all do string.format and define some string in a specifed format.
I have a string which is always formatted in a way like this:
const string myString = string.Format("pt:{0}-first:{1}", inputString);
To get {0}, I can always check for pt:{ and read till }.
But what is the best/recommended way to extract {0} & {1} from the above variable myString ?
A Regex version of answer, but again, assuming your input doesnt contain '-'
var example = = "pt:hello-first:23";
var str = "pt:(?<First>[^-]+)-first:(?<Second>[^%]+)";
var match = new Regex(str).Match(example);
var first = match.Groups["First"].Value;
var second = match.Groups["Second"].Value;
It might be a good idea that you define what your variable can/cannot contain.
Not sure if this is the best way to do it, but it's the most obvious:
string example = "pt:123-first:456";
var split = example.Split('-');
var pt = split[0].Substring(split[0].IndexOf(':') + 1);
var first = split[1].Substring(split[1].IndexOf(':') + 1);
As Shawn said, if you can guarantee that the variables wont contain either : or - this will be adequate.

C# String Format give wrong result

I'm trying to format a string of 6 digits with the following format:
1234/56.
I'm using the following:
string.Format("123456", "{0000/00}");
Result 123456
Try something like
var number = int.Parse("123456");
var formattedNumber = number.ToString("####/##", CultureInfo.InvariantCulture);
Edit to include zero fill (if required):
var number = int.Parse("123456");
var formattedNumber = number.ToString("####/##", CultureInfo.InvariantCulture).PadLeft(7,'0');
You will still have issues with any number below 10 (i.e "000009") showing up as 0000/9. In which you are probably better off with a substring modification like below.
var text = "123456";
var formattedNumber = text.Substring(0, 4) + "/" + text.Substring(4, 2);
Please try the below code.
string.Format("{0:####/##}",123456)
I tested the code and is working.
For reference on string formatting please visit:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings
If you are using numbers I would use #rob-s 's example above. If you are dealing with actual strings then you can use the following code sample.
var value = "123456";
var index = value.Length - 2;
var formattedValue = $"{value.Substring(0, index)}/{value.Substring(index)}";
Console.WriteLine(formattedValue);
Your output will look like what you have described in your question.
1234/56

Date column is not set properly in open XML Excel

I am trying to copy the data in excel sheet but it does not show properly it is show like ####### but I want 17-09-2016 like this.kindly suggest me what code I am write to export the excel in proper format.
Code:
var rngTable2 = ws.Range("A:G");
var rngHeaders2 = rngTable2.Range("F4:G4");
rngHeaders2.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.General;
rngHeaders2.Style.Alignment.Vertical = XLAlignmentVerticalValues.Bottom;
Date comes from this code:
Label lblpkgdate = (Label)gvvessel.Rows[j].FindControl("lblpackagedate");
string myVal1 = lblpkgdate.Text;
ws.Cell("F" + index5.ToString("dd/MM/yyyy")).Value = myVal1;
index5++;
Ultimately, it seems like you're trying to get a date from a label and then put this value into a load of cells within column F somewhere. I'm guessing you have this within a for loop as well seeing as you're incrementing index5. So something like this should work:
//Make column F a date column. Alter to a specific range if the whole column shouldn't be of date type.
Range rg = ws.Range("F:F");
rg.EntireColumn.NumberFormat = "DD/MM/YYYY";
var lblpkgdate = (Label).gvvessel.Rows[j].FindControl("lblpackagedate");
//Convert lblpkgdate text to DateTime object assuming format of dd/MM/yyyy to ensure it is actually a date.
DateTime pkgDate = DateTime.ParseExact(lblpkgdate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
for(int i = 1, i < YourMaxRowValue, i++)
{
ws.Cell("F" + i).Value = pkgDate;
}
NOTE - I've altered index5 to 'i' as this is less misleading if you're looping. I've also altered myVal1 to pkgDate as I think this is more meaningful.
you can use NumberFormat
Label lblpkgdate = (Label)gvvessel.Rows[j].FindControl("lblpackagedate");
string myVal1 = lblpkgdate.Text;
ws.Cell("F" + index5.ToString()).Style.NumberFormat.Format = "DD-MM-YYYY";
ws.Cell("F" + index5.ToString()).Value = myVal1;
index5++;

NPOI: Create a cell containing two differently sized strings

so as the title intends, I want to creaete a cell in a NPOI 2.1.3-Workbook containing 2 strings: A "normal"-sized string and a "small"-sized string. => I want to change the font-size for a part of the cell.
My code so far:
var planCell = planRow.CreateCell(lineCnt + 1);
var planCellStyle = workbook.CreateCellStyle();
planCellStyle.WrapText = true;
planCellStyle.VerticalAlignment = VerticalAlignment.Top;
planCellStyle.Alignment = HorizontalAlignment.Left;
var font = workbook.CreateFont();
font.FontName = HSSFFont.FONT_ARIAL;
font.FontHeightInPoints = 16;
font.Boldweight = (short)FontBoldWeight.Bold;
planCellStyle.SetFont(font);
planCell.CellStyle = planCellStyle;
string planTitleContent = string.Empty;
... (some logic to get desired string for planTitleContent)
string planInfoContent = string.Empty;
... (some logic to get desired string for planInfoContent)
planCell.SetCellValue(planTitleContent + "\n\n"+planInfoContent);
To be precise, I want the "planInfoContent"-part to be shown in a smaller font-size than the "planCellContent"-part. I searched a lot, but I just found the CellStyle-value which applies to the whole cell. So I hope I am missing something for two cells are not really an option.
Just figured it out myself :)
First, create 2 fonts of the desired format (for me and for simplicities sake, only the font size is of relevance):
var font1 = excel.CreateFont();
font1.FontName = HSSFFont.FONT_ARIAL;
font1.FontHeightInPoints = 12;
font1.Boldweight = (short)FontBoldWeight.Normal;
var font2 = excel.CreateFont();
font2.FontName = HSSFFont.FONT_ARIAL;
font2.FontHeightInPoints = 8;
font2.Boldweight = (short)FontBoldWeight.Normal;
Then, after you got your string(s), make use of (N)POIs applyFont-Method.
One of its implementations in NPOI has the following signature:
applyFont(int startIndex, int endIndex, IFont font)
so now, having string planTitleContent and string planInfoContent, the remaining steps are pretty obvious: Just create an Instance of IRichTextString and add your strings to it via constructor-parameter. Then, apply the wanted fonts via the index like so:
IRichTextString formattedCellContent = new HSSFRichTextString(planTitleContent + "\n"+planInfoContent);
richString.ApplyFont(0, planTitleContent.Length, font1);
richString.ApplyFont(planTitleContent.Length + 1, (planTitleContent + "\n" + planInfoContent).Length, font2);
planCell.SetCellValue(formattedCellContent);
so, this works like a charm for me. Hope it helps some other folks out!

Find and replace content within string (C#)

The below string is coming from a DIV tag. So I have enclosed the value below.
String cLocation = "'target="_blank'></a><img alt='testimage.jpg' src='/SPECIMAGE/testimage.jpg'"
I would like to replace in the above string by changing "src="/" with "src='xyz/files'".
I have tried the typical string.Replace("old","new") but it didn't work.
I tried the below,
cNewLocation ="xyz/files";
cNewString = cLocation.Replce("src='/'", "src='" + cNewLocation + "'/")
It didn't work.
Please suggest.
If I'm understanding what you're asking, you could use Regex to replace the string like so:
var cNewString = Regex.Replace(cLocation, #"src='/.*/", "src='" + newLocation + "/");
EDIT : I modified the regular expression to replace src='/.../ with src='{newLocation}/
you might try looking at the Replace command in c#.
so mystring = srcstring.Replace("old", "New");
http://msdn.microsoft.com/en-us/library/system.string.replace%28v=vs.71%29.aspx
possible replace the / in the string with //?
You can do the following:
string cLocation = "'target='_blank'></a><img alt='testimage.jpg' src='/SPECIMAGE/testimage.jpg'";
cLocation = cLocation.Replace("src='/'", "src='xyz/files'");
This fixes the problem:
int start = cLocation.IndexOf("src='") + 5;
int end = cLocation.LastIndexOf("'");
string xcLocation = cLocation.Remove(start, end - start);
string cLocation = xcLocation.Insert(start , "xyz/files");

Categories