ClosedXML Adding Formula creates unreadable content - c#

I am adding a formula to worksheet using C# closedxml but it is coming back as unreadable content. I think the reason is the slashed that I added to the formula but I need the slashes to escape the quotes because I need the quotes in the formula. How else can I do this?
Here is my code:
CodeWorksheet.Range(CodeWorksheet.Cell(2, 25).Address, CodeWorksheet.Cell(CodeWorksheet.LastRowUsed().RowNumber(), 25).Address).FormulaR1C1 = "=IF(SUM(RC[-6]:RC[-1])>0,\" + \",\")";

I think you only have one double quote in the "if false" part of your formula. Try changing
=IF(SUM(RC[-6]:RC[-1])>0,\" + \",\")
to
=IF(SUM(RC[-6]:RC[-1])>0,\" + \",\"\")

Related

Using Regex.Replace function in c# program to replace a string(data) with "data"?

I want to make use of Regex.Replace function to replace data in the format
05-11
to
"05-11"
so that excel can read it as a string.
Excel is converting the data to 05-Nov even though that particular column is defined as char.
In my application code, I have the below piece of code to replace any data that starts with a dash (-) with double quotes, "data"
var newString = Regex.Replace(data, #"^(-.*)$", "=\"$0\"");
How can I make use of this function to replace any data which are like
'05-11', '15-2019'
with
"05-11", "15-2019"
for the excel to read them as a string not as date format.
Unfortunately Excel does not accept " as an indicator of a text column, the only way to be sure is to proceed the value with a single quote.
var newstring = Regex.Replace(data, #"\b""?(\d\d-(?:\d\d)?\d\d)""?\b", "\"=\"\"$0\"\"\"");
This finds possibly double-quoted date strings that constitute the whole column value, and outputs it quoted with an equals sign and double quotes.
Unfortunately this special formatting is lost if you save as CSV from inside Excel and try to reload.
See this question for details.

Enclosing every field with double quotes in CSV file using c#

I have found several threads on people wishing to REMOVE quotes from their CSV file, but not adding them. And the ones I have found about adding quotes have not helped my case.
I'm using Microsoft.Office.Interop.Excel and am creating a CSV file that will be read by a program that oddly enough requires each field to be in double quotes. However when I write to a cell using, for example:
xlSheet.Cells[1,1] = "\"" + id + "\"";
my output is """id"""
Is there any fix for this? My client also wishes to be able to open the file in Excel, hence my use of Microsoft.Office.Interop
You dont really have to write to the file using Microsoft.Office.Interop.Excel instead just write to a file using a StreamWriter with the name of the file as Your_File.csv. And still u can open this CSV file using Excel. Remember to use proper delimiters in the CSV file. Hope this helps.
Excel may be interpreting your "id" value as a literal string rather than a number, then adding additional quotes to it when it converts it to CSV.
Rather than adding quotes, store the value as a string instead of a number:
xlSheet.Cells[1,1] = id.ToString();

CSV printing issue

I have a program the writes to a csv two columns. One is a ratio, of the form 1:100, or something similar, and the other is a score.
These values are stored in a Dictionary and printed as follows:
foreach (String s in p.normalizedScore.Keys)
{
sw.WriteLine(s + DELIM + p.normalizedScore[s]);
}
where sw is a StreamWriter and DELIM is a comma. The outputs is as follows:
1:10,7.498378506
0.111111111,18.46320676
0.736111111,30.08283816
1:10000 ,40.80688802
1:100000 ,51.93716854
1:1000000,62.89993635
1:10000000,73.54010349
The scores are all correct, but 2 of the ratios are printed incorrectly (it should be increasing 10 fold, so there should be a 1:100 and a 1:1000). When I enter the debugger, I find that at the time of printing, it's still reading all the ratios correctly, meaning I can't locate any place in my code where the ratios are wrong. Does anyone have an idea as to what the problem might be?
Edit: The above output was copied directly from Excel, but if I look at it in Notepad, the data seems fine, so it seems to me the problem is with Excel. (Still don't know what it is mind you.)
As per the comments - this was an Excel formatting issue, not a code issue.
Adding Cory's comment to the answer because I think it adds significant value:
If you put quotes around your ratios, Excel shouldn't try any funny
business with formatting (you won't see the quotations in Excel,
that's just part of the CSV spec for qualifying your values).
Do not just double click the file and open in excel. Open a new worksheet and import from text file. You will then specify it's a column of text - or you can create your csv with a text qualifier and use that in the import as well.
alternatively you can add a space in front of your s variable.
sw.WriteLine(" "+ s + DELIM + p.normalizedScore[s]);
' 1:10' won't be treated as an expression.

C# Excel interop, put a line break in the text of a cell in a Excel

I am writing an Excel sheet using interop. In the sheet I need to put a set of sentences in to a cell. The text should be in a line break manner. How can I achieve this?
Thanks in advance.
It was done by either entering "\r\n" or Environment.NewLine. And also must remember to make WrapText property true in order to make the line breaks visible.
you can add style to cells programically as bellow
worksheet.Cells.Style.WrapText = true;
New line within an Excel cell is the LF character, which is "\n" in C#. And do not forget to set the WrapText property of the cell to TRUE.
New line within an Excel cell is the LF character, which is "\n" in C#.
In VB, or VBA, I used to use vbCrLf (case sensitive) to separate sentences to separate lines in an Excel's Cell like the following:
Dim myString As String
myString = "First sentence" & vbCrLf & "Second sentence"
ActiveCell.ForumulaR1C1 = myString
In C#, I am rather confident that the C# equivalent of VB's vbCrLf is "\r\n", hence:
myString = "First sentence\r\n" + "Second sentence"
I have encountered this problem but difference is I do not have access to the worksheet in code as I only pass it to memorystream then create file as .csv type.
foreach (var s in propertyValues)
streamWriter.WriteLine(s);
streamWriter.Flush();
memoryStream.Seek(0, SeekOrigin.Begin);
the I use it from here.
subjExportData.FileStream = stream;
subjExportData.FileName = string.Format("SubjectExport_{0}.csv", DateTime.Now.ToString("ddMMyyyy_HHmm"));
So the suggestion here to set text or cell wrap is not an option. Got it working using the above answer plus put a double quote before and after the text/string. The replace is to handle when the sentence has a double quote too inside it. So this solution handles, new line, comma and double quotes inside a sentence or paragraph.
if (value.ToString().Contains("\n"))
{
value = value.ToString().Replace("\n", "\r\n");
sb.Append('"'+ value.ToString().Replace(#"""", #"""""") + '"'+ ",");
}
the answer of this issue is to add a "quot" in front and at the end of the string you want to display in your excel cell. In C# it would be something like (Convert.ToChar(34) + stringToExport + Convert.ToChar(34))

Excel adds extra quotes on CSV export

I've recently created an application which adds items to a Database by CSV. After adding items I realized that lots of my values had extra quotes (") that weren't needed and this was messing up my ordering.
The problem is that when exporting to a CSV from Excel, Excel adds extra quotes to all of my values that already have a quote in them. I've shown the difference below:
Original Item: Drill Electric Reversible 1/2" 6.3A
Exported Item: "Drill Electric Reversible 1/2"" 6.3"
Note: the CSV export is adding three (3) extra quotes ("). Two on the ends, and one after the original intended quote.
Is there a setting I can change, or a formatting property I can set on the Excel File/Column? Or do I have to live with it and remove these quotes in my back-end code before adding them to the Database?
This is entirely normal. The outer quotes are added because this is a string. The inner quote is doubled to escape it. Same kind of thing you'd see in a SQL query for example. Use the TextFieldParser class to have tried and true framework code care of the parsing of this for you automatically.
That's standard.
The values within a CSV file should have quotes around them (otherwise commas and linebreaks inside a field may be misinterpreted).
The way to escape a quote within a field is to double it, just as you are seeing.
I suggest you read about the basic rules of CSV:
CSV is a delimited data format that has fields/columns separated by the comma character and records/rows terminated by newlines. Fields that contain a special character (comma, newline, or double quote), must be enclosed in double quotes. If a line contains a single entry which is the empty string, it may be enclosed in double quotes. If a field's value contains a double quote character it is escaped by placing another double quote character next to it. The CSV file format does not require a specific character encoding, byte order, or line terminator format.
(emphasis mine)
You could try exporting from Excel as TAB delimited files. I find it easier to parse.
Replace all characters Right Double Quotation Mark by characters Left Double Quotation Mark. They look similar, Excel will be confused and let the text unchanged.
This solution will only help if your end output is HTML. This is the javascript solution so obviously you'll need to redo this in C# or whichever language you're working in:
base = base.replace(/""/gi, '"');
base = base.replace(/'/gi, ''');
Apply this before you parse the CSV.
Another approach would be to use the Unicode Character "DOUBLE PRIME"
http://www.fileformat.info/info/unicode/char/2033/index.htm
in your Excel data. To export from Excel into a UTF-8 or UTF-16 .csv you'll have to provide a schema.ini with an appropriate CharacterSet property. Obviously, the tool you use to import the .csv into your database has to be Unicode aware too.
Depending on the DBMS a more direct way of data transfer (SELECT/INSERT ... INTO ... IN ) can be used, thereby eliminating the .csv entirely.

Categories

Resources