In my case I create a CSV file using StreamWriter in c# using code below:
[System.Web.Http.HttpPost]
public ActionResult createAllSubscribtionsExcelFile()
{
int ID = Convert.ToInt32(Request.Params["ID"]);
long totalRecords;
var Members = Services.MemberService.GetAll(0, int.MaxValue, out totalRecords);
string baseURL = string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"));
string packageName = Umbraco.Content(ID).Name;
string currentPath = Server.MapPath("/") + packageName;
string returnPath = baseURL + "/" + packageName;
string orderNumber = "none"; string price = "none"; string theBillNumber = "none";
List<RootObject> packages = null;
if (!System.IO.File.Exists(currentPath))
{
System.IO.File.Create(currentPath);
}
using (StreamWriter sr = new StreamWriter(currentPath + ".csv", false, Encoding.UTF8))
{
foreach (var member in Members)
{
var NestedPackages = member.GetValue<string>("packages");
if (NestedPackages != null)
{
packages = JsonConvert.DeserializeObject<List<RootObject>>(NestedPackages);
}
if (NestedPackages != null)
{
foreach (var package in packages)
{
var udi = package.package;
var content = Umbraco.Content(udi);
orderNumber = package.orderNumber;
price = package.theAmountPaid.ToString();
theBillNumber = package.theBillNumber;
sr.WriteLine("" + "," + orderNumber.Replace(',', ' ').Replace('/', ' ') + "," + price.Replace(',', ' ').Replace('/', ' ')
+ "," + theBillNumber.Replace(',', ' ').Replace('/', ' '));
}
}
}
sr.Close();
}
return Redirect(returnPath + ".csv");
}
In my case theBillNumber = "16744817032020146676", but the value that shown in the excel sheet like that
"16744817032020100000" (the last 5 digits Equuleus zero).
How can I fix this problem, Please help.
A tiny trick!
Using c# I create a .CSV with the single line:
12/25/2021,James,'1836542348674987512345363,12
Note the single quote at the start of the really big number.
If we do not pre-pend a text character, Excel will treat the number as a super big integer with way more than 15 decimal digits. Excel will automatically convert the trailing numerals into zeros. The single quote tells Excel to leave all the numerals alone.
Once Excel opens the .CSV normally, all the numerals are present, but the cell begins with the single quote. The following VBA will open the .CSV and convert any leading single quote into a PrefixCharacter.
Then using Excel VBA:
Sub dural()
Workbooks.Open Filename:="C:\Users\garys\Desktop\x.csv"
Dim cell As Range
For Each cell In ActiveSheet.UsedRange
v = cell.Value
If Left(v, 1) = "'" Then
cell.Clear
cell.NumberFormat = "#"
cell.Value = v
End If
Next cell
End Sub
I get:
As you see by comparing the value in the Formula Bar to the value in the cell, the single quote is no longer part of the number. It is just a PrefixCharacter.
This kind of handling is useful for:
long phone numbers
USPS tracking numbers
banking account and routing numbers
etc.
I had this issue before, and I hadn't found a solution for it, I had to add an underscore before the number so it would be treated as text
As documented on the Microsoft Learn website, large numbers (lengths greater than 15 digits) are automatically converted to zeroes.
Hence as a workaround, prefix such large digits with a single quote.
Last digits are changed to zeros when you type long numbers in cells of Excel
Related
I'm having two problems with reading my .csv file with streamreader. What I'm trying to do is get the values, put them into variables which I'll be using later on, inputting the values into a browser via Selenium.
Here's my code (the Console.Writeline at the end is just for debugging):
string[] read;
char[] seperators = { ';' };
StreamReader sr = new StreamReader(#"C:\filename.csv", Encoding.Default, true);
string data = sr.ReadLine();
while((data = sr.ReadLine()) != null)
{
read = data.Split(seperators);
string cpr = read[0];
string ydelsesKode = read[1];
string startDato = read[3];
string stopDato = read[4];
string leverandoer = read[5];
string leverandoerAdd = read[6];
Console.WriteLine(cpr + " " + ydelsesKode + " " + startDato + " " + stopDato + " " + leverandoer + " " + leverandoerAdd);
}
The code in and of itself works just fine - but I have two problems:
The file has values in Danish, which means I get åøæ, but they're showing up as '?' in console. In notepad those characters look fine.
Blank values also show up as '?'. Is there any way I can turn them into a blank space so Selenium won't get "confused"?
Sample output:
1372 1.1 01-10-2013 01-10-2013 Bakkev?nget - dagcenter ?
Bakkev?nget should be Bakkevænget and the final '?' should be blank (or rather, a bank space).
"Fixed" it by going with tab delimited unicode .txt file instead of .csv. For some reason my version of excel doesn't have the option to save in unicode .csv...
Don't quite understand the problem of "rolling my own" parser, but maybe someday someone will take the time to explain it to me better. Still new-ish at this c# stuff...
There are other similar questions that have been asked and answered, but none of those answers work in what I'm trying to do, or there isn't enough information for me to know how to implement it in my own code. I've been at it for two days and now must ask for help.
I have a script task in an SSIS package where I need to do a match and replace on a large XML file that contains thousands of Record Identifier tags. Each one contains a number. I need those numbers to be consecutive and increment by one. For example, within the xml file, I am able to find tags that appear like this:
<ns1:recordIdentifier>1</ns1:recordIdentifier>
<ns1:recordIdentifier>6</ns1:recordIdentifier>
<ns1:recordIdentifier>223</ns1:recordIdentifier>
<ns1:recordIdentifier>4102</ns1:recordIdentifier>
I need to find and replace those tags with consecutive increments like so:
<ns1:recordIdentifier>1</ns1:recordIdentifier>
<ns1:recordIdentifier>2</ns1:recordIdentifier>
<ns1:recordIdentifier>3</ns1:recordIdentifier>
<ns1:recordIdentifier>4</ns1:recordIdentifier>
The code I have so far is causing all the numbers to be "1" with no incrementation.
I've tried dozens of different methods, but nothing has worked yet.
Any ideas as to how I can modify the below code to increment as desired?
public void Main()
{
string varStart = "<ns1:recordIdentifier>";
string varEnd = "</ns1:recordIdentifier>";
int i = 1;
string path = Dts.Variables["User::xmlFilename"].Value.ToString();
string outPath = Dts.Variables["User::xmlOutputFile"].Value.ToString();
string ptrn = #"<ns1:recordIdentifier>\d{1,4}<\/ns1:recordIdentifier>";
string replace = varStart + i + varEnd;
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null && i>0)
{
File.WriteAllText(outPath, Regex.Replace(File.ReadAllText(path),
ptrn, replace));
i++;
}
}
}
You were on the right path with the Replace method, but will need to use the MatchEvaluater parameter when you increment.
string inputFile = Dts.Variables["User::xmlFilename"].Value.ToString();
string outPutfile = Dts.Variables["User::xmlOutputFile"].Value.ToString();
string fileText = File.ReadAllText(inputFile);
//get any number between elements
Regex reg = new Regex("<ns1:recordIdentifier>[0-9]</ns1:recordIdentifier>");
string xmlStartTag = "<ns1:recordIdentifier>";
string xmlEndTag = "</ns1:recordIdentifier>";
//assuming this starts at 1
int incrementInt = 1;
fileText = reg.Replace(fileText, tag =>
{ return xmlStartTag + incrementInt++.ToString() + xmlEndTag; });
File.WriteAllText(outPutfile, fileText);
I'm using an ASP.NET application which exports my clients data to CSV, I need my clients Phone number to be with the leading Zero.
I need the phone numbers to be without "-" and without quotations, and due to the nature of my application I cannot use 3rd party products such as EPPLUS.
I've tried to put a space and let the CSV "understand" that I need the phone number as text , but that doesn't seem right.
I would like to know how to make the excel include the leading zero , without using 3rd party products.
Thanks
Change the data that is saved in the csv with the following format:
="00023423"
CSV example:
David,Sooo,="00023423",World
This will show 00023423 in excel and not 23423.
public void CreatingCsvFiles(Client client)
{
string filePath = "Your path of the location" + "filename.csv";
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
}
string delimiter = ",";
string[][] output = new string[][]{
new string[]{ "=\"" + client.phone + "\"", client.name }
};
int length = output.GetLength(0);
StringBuilder sb = new StringBuilder();
for (int index = 0; index < length; index++)
sb.AppendLine(string.Join(delimiter, output[index]));
File.AppendAllText(filePath, sb.ToString());
}
Inspired from http://softwaretipz.com/c-sharp-code-to-create-a-csv-file-and-write-data-into-it/
The important part :
"=\"" + client.phone + "\"", client.name
If the phone number is an int, of course you add .toString().
Print phone number to CSV with prepended ' (single quote), so it looks like:
"Some Name","'0000121212"
Excel should treat this 0000121212 as string then.
I believe converting the number into a formula like the accepted answer might not be a helpful solution for all.
The alternate solution I went with is to just add a tab space before the integer value.
Example:
Taking phoneNumber as a string variable which contains our int value
Solution:
"\t" + phoneNumber
If you know already how much numbers has to be inside phone you can do like this
phoneNumber.ToString("000000000000")
In this example I consider that phoneNumber is an int and required length of numbers is 12.
I have productID="ab1002" which is in string format.
productID is not always start with ab it might be xy,ptz.So i want to split the numeric part of ID and increase by 1.
means
string productID="ab1002";
want a result
string newProductID="ab1003";
How to get this.thanks for help.
To remove the characters:
string sNumbers = Regex.Replace(productID,"[^A-Z][a-z]",String.Empty); // To remove letters
string sText = Regex.Replace(productID,"[^0-9]",String.Empty); // To remove numbers
string iTmp = int.Parse(sNumbers); // Convert to integer
iTmp++;
string newProductID = sText + iTmp.ToString();
Would you please try with below code, this works fine according to you, thanks for your time
productID = (Regex.Replace(productID, "[0-9]", String.Empty)) +
(Convert.ToInt32(Regex.Replace(productID, "[a-z]", string.Empty, RegexOptions.IgnoreCase)) + 1).ToString();
I am generating 35 strings which have the names ar15220110910, khwm20110910 and so on.
The string contains the name of the Id (ar152,KHWM), and the date (20110910). I want to extract the Id, date from the string and store it in a textfile called StatSummary.
My code statement is something like this
for( int 1= 0;i< filestoextract.count;1++)
{
// The filestoextract contains 35 strings
string extractname = filestoextract(i).ToString();
statSummary.writeline( extractname.substring(0,5) + "" +
extractname.substring(5,4) + "" + extractname.substring(9,2) + "" +
extractname.substring(11,2));
}
When the station has Id containing 5 letters, then this code executes correctly but when the station Id is KHWM or any other 4 letter name then the insertion is all messed up. I am running this inside a loop. So I have tried keeping the code as dynamic as possible. Could anyone help me to find a way without hardcoding it. For instance accessing the last 8 elements to get the date??? I have searched but am not able to find a way to do that.
For the last 8 digits, it's just:
extractname.Substring(extractname.Length-8)
oh, I'm sorry, and so for your code could be:
int l = extractname.Length;
statSummary.WriteLine(extractname.substring(0,l-8) + "" +
extractname.Substring(l-8,4) + "" + extractname.Substring(l-4,2) + "" +
extractname.Substring(l-2,2));
As your ID length isn't consistent, it would probably be a better option to extract the date (which is always going to be 8 chars) and then treat the remainder as your ID e.g.
UPDATED - more robust by actually calculating the length of the date based on the format. Also validates against the format to make sure you have parsed the data correctly.
var dateFormat = "yyyyMMdd"; // this could be pulled from app.config or some other config source
foreach (var file in filestoextract)
{
var dateStr = file.Substring(file.Length-dateFormat.Length);
if (ValidateDate(dateStr, dateFormat))
{
var id = file.Substring(0, file.Length - (dateFormat.Length+1));
// do something with data
}
else
{
// handle invalid filename
}
}
public bool ValidateDate(stirng date, string date_format)
{
try
{
DateTime.ParseExact(date, date_format, DateTimeFormatInfo.InvariantInfo);
}
catch
{
return false;
}
return true;
}
You could use a Regex :
match = Regex.Match ("khwm20110910","(?<code>.*)(?<date>.{6})" );
Console.WriteLine (match.Groups["code"] );
Console.WriteLine (match.Groups["date"] );
To explain the regex pattern (?<code>.*)(?<date>.{6}) the brackets groups creates a group for each pattern. ?<code> names the group so you can reference it easily.
The date group takes the last six characters of the string. . says take any character and {6} says do that six times.
The code group takes all the remaining characters. * says take as many characters as possible.
for each(string part in stringList)
{
int length = part.Length;
int start = length - 8;
string dateString = part.Substring(start, 8);
}
That should solve the variable length to get the date. The rest of the pull is most likely dependent on a pattern (suggested) or the length of string (when x then the call is 4 in length, etc)
If you ID isn't always the same amount of letters you should seperate the ID and the Date using ',' or somthing then you use this:
for( int 1= 0;i< filestoextract.count;1++)
{
string extractname = filestoextract[i].ToString();
string ID = extractname.substring(0, extractname.IndexOf(','));
string Date = extractname.substring(extractname.IndexOf(','));
Console.WriteLine(ID + Date);
}