Number format in Word document - c#

I have some fields in an Word document with instructional text, for example like this one:
{ MERGEFIELD MyField1 \# "000" }
I'm reading those fields using OpenXML SDK, as shown here, and replacing them with some data.
I'm applying the number format that is specified in the field to my data, like this:
string fieldFormat = "000";
int data = 1234;
string fieldValue = data.ToString(fieldFormat);
In most cases this works great, but now I got a document that has "xxx" as a number format and when using the above I get "xxx" for fieldValue.
string fieldFormat = "xxx";
int data = 1234;
string fieldValue = data.ToString(fieldFormat); // Problem!
I saw that .NET doesn't support this in Custom numeric format, but Word supports this in a way that it removes any digits that come after the "x" symbols place.
So for the above, it should result in "234". How can I do that in C#?
EDIT, added some additional examples:
int number = 1158;
string format1 = "x";
string format2 = "xx";
string format3 = "x#";
string format4 = "x,###";
string format5 = "x,xxx";
string format6 = "x##.00";
string format7 = "xxxxxxx.00";
Console.WriteLine("(number + format1) should result to: 8");
Console.WriteLine("(number + format2) should result to: 58");
Console.WriteLine("(number + format3) should result to: 58");
Console.WriteLine("(number + format4) should result to: 1,158");
Console.WriteLine("(number + format5) should result to: 1,158");
Console.WriteLine("(number + format6) should result to: 158.00");
Console.WriteLine("(number + format7) should result to: 1158.00");

Related

String Manipulation and splitting string

string url = "test:app:https://test#hotmail.co.uk:Test
I need to split this up to display as follows
string first = "app";
string second = "https://test#hotmail.co.uk:Test";
i have tried the following but falls over on the last colon.
string remove= "";
remove= url.Replace("test:", "");
string first= remove.Substring(remove.LastIndexOf(':') + 1);
string second= remove.Substring(0, remove.IndexOf(':'));
Doing this i get
first = "app";
second = "Test";
When i need
first = "app";
second = "https://test#hotmail.co.uk:Test";
Your use of LastIndexOf is just a bit wonky.
string url = "test:app:https://test#hotmail.co.uk:Test";
string remove = url.Replace("test:", "");
string first = remove.Substring(0, remove.IndexOf(":"));
string second = remove.Substring(remove.IndexOf(first) + first.Length + 1);
First grab the app, and we can use the location of app to derive the rest of the string. Because the last index of : would be the one in :Test. We don't want the last index of :. Instead we just want whatever comes after app.
As everything is prefixed with test: you can use a starting position after that and then split after the first occurrance of the : character.
const int IndexOfPrefix = 5; // start position after "test:"
string url = "test:app:https://test#hotmail.co.uk:Test";
var indexOfApp = url.IndexOf(':', IndexOfPrefix);
var part1 = url.Substring(IndexOfPrefix, indexOfApp - IndexOfPrefix);
var part2 = url.Substring(indexOfApp + 1);
Console.WriteLine(part1);
Console.WriteLine(part2);
Something like this should do the trick:
public void ManipulateStrings()
{
string url = "test:app:https://test#hotmail.co.uk:Test";
url = url.Replace("test:", "");
string first = url.Substring(0, url.IndexOf(':'));
string second = url.Substring(url.IndexOf(':') + 1);
}
This basically removed test: from your string, then assigns first and second their values without creating string remove = "" for no reason.
You can use Split(Char[], Int32) to get the desired number of elements (3 : the first unwanted part, the first expected part and the remaining) along with Skip() to remove the unwanted one :
string url = "test:app:https://test#hotmail.co.uk:Test";
var splitted = url.Split(new [] { ':' }, 3).Skip(1).ToArray();
var first = splitted[0];
var second = splitted[1];
Console.WriteLine(first);
Console.WriteLine(second);
This outputs
app
https://test#hotmail.co.uk:Test
Another way to do that is using regular expressions :
The pattern :(?<first>.*?):(?<second>.*) will :
: search for the characters :
(?<first>.*?) creates a group named first that will match any number of any character (lazy)
: search for the characters :
(?<second>.*) creates a group named second that will match any number of any character (greedy)
In example :
string url = "test:app:https://test#hotmail.co.uk:Test";
var pattern = ":(?<first>.*?):(?<second>.*)";
var regex = new Regex(pattern); // using System.Text.RegularExpressions;
Match match = regex.Match(url);
if (match.Success)
{
var first = match.Groups["first"].Value;
var second = match.Groups["second"].Value;
Console.WriteLine(first);
Console.WriteLine(second);
}
This outputs
app
https://test#hotmail.co.uk:Test
you need to change the variable with name "first" to "second" and to change the variable with name "second" to "first"
This is your code:
string url = "test:app:https://test#hotmail.co.uk:Test";
string remove = "";
remove = url.Replace("test:", "");
string second = remove.Substring(0, remove.IndexOf(':'));
string first = remove.Substring(remove.IndexOf(":") + 1);
and this is the correct code:
string url = "test:app:https://test#hotmail.co.uk:Test";
string remove = "";
remove = url.Replace("test:", "");
string first = remove.Substring(0, remove.IndexOf(':'));
string second = remove.Substring(remove.IndexOf(":") + 1);

C# extract data from csv

I have a CSV file like this:
field1,field2,field3,field4,...,fieldN
1,2,3,,...,N
and I want to extract exactly the 14th record of the second row.
I've tried this code:
string nomeFile = "externalSourceMsg " + this.DataSource.CodSorgEst + this.DataSource.CodIdSorgEst + ".csv";
string content = "Field1,Field2,Field3,Field4,Field5,Field6,Field7" + Environment.NewLine;
content += externalMessage.ToString();
content = content.Replace(',', ';');
int i = 0;
while (content){
int field;
if(i++ == 13)
field = content+i;
}
but it doesn't work. What did I do wrong?
Split the string and you can access fields by indexes.
string nomeFile = "externalSourceMsg " + this.DataSource.CodSorgEst + this.DataSource.CodIdSorgEst + ".csv";
string content = "Field1,Field2,Field3,Field4,Field5,Field6,Field7" + Environment.NewLine;
content += externalMessage.ToString();
content = content.Replace(',', ';');
// Split the string by your separator -> you will get an array filled with fields
string[] contentArr = content.Split(';');
// Access any field you'd like by indexes
var The14thField = contentArr[13];
Try:
// Read all lines and get the second (this can be done
// in more optimal way, just by reading two first lines)
var secondLine = File.ReadLines("Path")[1];
// Split byb comma and get 14th item in returned array
var entry = secondLine.Split(",")[13];

extract numerical values from string after dash (-)

I have string value like this Rs.100 - Rs.250 Now I want only 250 from this string.
I tried this but it's not getting output
var result = str.Substring(str.LastIndexOf('-') + 1);
UPDATE
string result = price.Text;
string[] final_result = result.Split('.');
dynamic get_result = final_result(1).ToString();
price.Text = final_result.ToString;
Try this code after getting the result of Rs.250.
var data = Regex.Match(result, #"\d+").Value;
Do it like this:
string str = "Rs.100-Rs.250";
var result = str.Substring(str.LastIndexOf('-') + 1);
String[] final_result = result.Split('.');
var get_result = final_result[1].ToString();
this will get 250 as you wanted.
try this
var result = ("Rs.100 - Rs.250").Split('-').LastOrDefault().Split('.').LastOrDefault();

dynamic substring in c#

I have a set of code in c# I want to store into the database what the user is entering in the textbox.
The user enters into the textbox like this
input namexyzpan9837663placeofbirthmumbailocationwadala
This is what user enters
(name: xyz pan: 9837663 place of birth: mumbai location: wadala)
Output into the database
xyz 9837663 mumbai wadala
OR
name xyzapan72placeofbirthgoalocationpanji
(> name: xyza pan: 72 place of birth: goa location: panji)
Output into the database
xyza 72 goa panji
name, age, location and placeofbirth are static but the value inside
them are dynamic
I know substring is helpfull but i don't know how to use it.
Use can use Split if the keywords are static :
string strMain = "namexyzpan9837663placeofbirthmumbailocationwadala";
var results = strMain.Split(new string[] { "name", "pan", "placeofbirth", "location" }, StringSplitOptions.RemoveEmptyEntries);
string name = results[0];
string pan = results[1];
string location = results[2];
You said you didn't know how to use Substring, well here it is working:
Note that the second parameter for this method is the length of the string to be taken and not the index at which to stop.
string strMain = "namexyzpan9837663placeofbirthmumbailocationwadala";
int indexOfName = strMain.IndexOf("name");
int indexOfPan = strMain.IndexOf("pan");
int indexOfBirth = strMain.IndexOf("placeofbirth");
int indexOflocation = strMain.IndexOf("location");
int effectiveIndexOfName = indexOfName + "name".Length;
int effectiveIndexOfPan = indexOfPan + "pan".Length;
int effectiveIndexOfBirth = indexOfBirth + "placeofbirth".Length;
int effectiveIndexOflocation = indexOflocation + "location".Length;
string name1 = strMain.Substring(effectiveIndexOfName, indexOfPan- effectiveIndexOfName);
string pan1 = strMain.Substring(effectiveIndexOfPan, indexOfBirth - effectiveIndexOfPan);
string birth1 = strMain.Substring(effectiveIndexOfBirth, indexOflocation - effectiveIndexOfBirth);
string location1 = strMain.Substring(effectiveIndexOflocation);
namenamepan9837663placeofbirthmumbailocationwadala works using the second method. But namepanpan9837663placeofbirthmumbailocationwadala is an interesting case that definitely needs a workaround.
Regex is designed for such case.
var input = #"namexyzpan9837663placeofbirthmumbailocationwadala";
var match = Regex.Match(input, #"^\s*"
+ #"name\s*(?<name>\w+?)\s*"
+ #"pan\s*(?<pan>\w+?)\s*"
+ #"placeofbirth\s*(?<placeOfBirth>\w+?)\s*"
+ #"location\s*(?<location>\w+)\s*" + #"$");
var name = match.Groups["name"].Value;
var pan = match.Groups["pan"].Value;
var placeOfBirth = match.Groups["placeOfBirth"].Value;
var location = match.Groups["location"].Value;

Want to assign HTML value to String variable

I want to assign HTML snippet to string variable.
something like -
string div = "<table><tr><td>Hello</td></tr></table>"; // It should return only 'Hello'
Please suggest.
string div = "<table><tr><td>Hello</td></tr></table>"; // It should return only 'Hello
var doc = new XmlDocument();
doc.LoadXml(div);
string text = doc.InnerText;
Do you also need the Jquery version of this?
If you are sure that the HTML won't change between the string you want to get, you can simply do a Substring between the two constants string and you will get your string into your variable.
const string prefix = "<table>";
const string suffix = "</table>";
string s = prefix + "TEST" + suffix ;
string s2 = s.Substring(prefix.Length, s.IndexOf(suffix, StringComparison.Ordinal) - prefix.Length);
Here is the Regex version:
const string prefix = "<table>";
const string suffix = "</table>";
string s = prefix + "TEST" + suffix;
string s2 = Regex.Match(s, prefix + "(.*)" + suffix).Groups[1].Value;

Categories