Adding a newline character within a cell (CSV) - excel

I would like to import product descriptions that need to be logically broken according by things like description, dimensions, finishes etc. How can I insert a line break so that when I import the file they will show up?

This question was answered well at Can you encode CR/LF in into CSV files?.
Consider also reverse engineering multiple lines in Excel. To embed a newline in an Excel cell, press Alt+Enter. Then save the file as a .csv. You'll see that the double-quotes start on one line and each new line in the file is considered an embedded newline in the cell.

I struggled with this as well but heres the solution. If you add " before and at the end of the csv string you are trying to display, it will consolidate them into 1 cell while honoring new line.
csvString += "\""+"Date Generated: \n" ;
csvString += "Doctor: " + "\n"+"\"" + "\n";

I have the same issue, when I try to export the content of email to csv and still keep it break line when importing to excel.
I export the conent as this: ="Line 1"&CHAR(10)&"Line 2"
When I import it to excel(google), excel understand it as string. It still not break new line.
We need to trigger excel to treat it as formula by:
Format -> Number | Scientific.
This is not the good way but it resolve my issue.

supposing you have a text variable containing:
const text = 'wonderful text with \n newline'
the newline in the csv file is correctly interpreted having enclosed the string with double quotes and spaces
'" ' + text + ' "'

On Excel for Mac 2011, the newline had to be a \r instead of an \n
So
"\"first line\rsecond line\""
would show up as a cell with 2 lines

I was concatenating the variable and adding multiple items in same row. so below code work for me. "\n" new line code is mandatory to add first and last of each line if you will add it on last only it will append last 1-2 character to new lines.
$itemCode = '';
foreach($returnData['repairdetail'] as $checkkey=>$repairDetailData){
if($checkkey >0){
$itemCode .= "\n".trim(#$repairDetailData['ItemMaster']->Item_Code)."\n";
}else{
$itemCode .= "\n".trim(#$repairDetailData['ItemMaster']->Item_Code)."\n";
}
$repairDetaile[]= array(
$itemCode,
)
}
// pass all array to here
foreach ($repairDetaile as $csvData) {
fputcsv($csv_file,$csvData,',','"');
}
fclose($csv_file);

I converted a pandas DataFrame to a csv string using DataFrame.to_csv() and then I looked at the results. It included \r\n as the end of line character(s). I suggest inserting these into your csv string as your row separation.
Depending on the tools used to generate the csv string you may need escape the \ character (\r\n).

Related

Excel Unicode appearing literally in cell value

I've got strings in an Excel table that have literal unicode values, i.e.   and I'm trying to compare them to another string which instead of the unicode string, has simply a space.
How do I do this? I tried this:
textref = replace(textref, ChrW$(160), " ")
as well as
textref = replace(textref, " ", " ")
and I can't seem to get it to work. Alternatively, is there a way to make Excel render the text as spaces?
Thanks in advance

Trailing Newlines in excel using MATLAB's writetable()

I'm trying to write a MATLAB table containing strings to excel using writetable(). I'd like the text in excel to end in a newline, that is a blank line with nothing written on it. However, I can't seem to get trailing newlines to write.
format_spec = 'r %6.4f\ng %6.4f\nb %6.4f\n';
vals = rand(4,5,3);
temp_str = cellfun(#(x) sprintf(format_spec,x) ,...
squeeze(mat2cell(permute(vals,[3 1 2]), ...
[size(vals,3)],[ones(1,size(vals,1))],[ones(1,size(vals,2))])) ,...
'UniformOutput',false);
temp_table = cell2table( temp_str );
writetable(temp_table,'test_table.xlsx'); %//where's my trailing newline?
xlswrite('test_cell.xlsx',table2cell(temp_table)); %//trailing newline preserved
With xlswrite the trailing newline is handled correctly, but to get the same functionality as writetable I have to add additional code to write the RowNames and VariableNames, and offset the excel location of the table contents by one row and one column. I guess I already have work around using xlswrite, but my question is if/how this can be done with writetable.
I reached out to the Mathworks regarding this issue and was told it is a bug. For now xlswrite must be used to preserve trailing newlines.

Removing unwanted data from text file

I have a large text file exported from an application that has three unwanted zeros in each row. The text file needs to be imported into another application and the zeros cause a problem.
Basically the unwanted three zeros per row need to be deleted. These zeros are always in the same location (same number of characters when counting from the left), but the location is somewhere in the middle. I have tried various things like importing the file into excel, removing the zeroes and then exporting as text file, but always have formatting problems with the exported text file.
Can someone suggest a solution or point me in the right direction?
something like this ? (quickly done)
Sub replaceInTx()
Dim inFile As String, outFile As String
Dim curLine As String
inFile = "x:\Documents\test.txt"
outFile = inFile & ".new.txt"
Open inFile For Input As #1
Open outFile For Output As #2
Do Until EOF(1)
Line Input #1, curLine
Print #2, Replace(curLine, "000", "", 6, 1, vbTextCompare)
Loop
Close #1
Close #2
End Sub
Alternatively, you can do that with any text editor that allows block selection (I like Notepad2, tiny, fast and portable)
I see you use excel a lot.
When you import the text file into excel do you use the import function and do you push the data into separate cells?
if the cell is numeric you could do the following:
=LEFT(TEXT(G5,"#"),LEN(TEXT(G5,"#"))-3)
if the cell is text:
=LEFT(G5,LEN(G5)-3)
G5 would the cell the data row/field is in.
curLine = Left(curLine, 104)
This will take the first 104 characters

Excel VbScript Quotes issue

I am using Vbscript to write some data into excel then i am saving this excel object as txt file. My problem here is after saving as text file some rows contains quotes ". Below is my code can some body help me recording this.
My Output text file is:
"Rules*V*ZBEA*892**0010*10*IBM-01**"
30,000.00*01/08/2012*21/08/2012****0000013556*01***2600
"Scale value* *********"
problem here is 1st and 3rd row starts and ends with quotes (" ").
code is
Dim objXL1,name
Set objXL1 = CreateObject("Excel.Application")
objXL1.Workbooks.Add
objXL1.Cells(1 ,1) = "Rules*V*ZBEA*892**0010*10*IBM-01** "
objXL1.Cells(2,1) = "30,000.00*01/08/2012*21/08/2012****0000013556*01***2600"
objXL1.Cells(3 ,1) = "Scale value* *********"
name = objXL1.GetSaveAsFilename(,"Text(MS-DOS)(*.txt),*.txt")
objXL1.ActiveWorkbook.SaveAs name ,21 ,,21
objXL1.ActiveWorkbook.Close 0
objXL1.quit
And here once more issue is I am using SaveAs method for getting file name. When execution comes to this line the file save dialog box hiding behind the main IE window is there any way to get this save dialog box in focus?
I assume this is because of the whitespace. In your code there is a trailing whitespace in the frist line.
"Rules*V*ZBEA*892**0010*10*IBM-01** "
-----------------------------------^-
If you would export multiple cells you would need to encapsualte those cells to recognize where a cell value begins and ends.

Export Excel : Avoid stripping the leading zeros

I am Export a data to Excel Sheet in C#.Net. There i am having column which has the data like "00123450098". The data is exported without the first zero's. I want to show the data as it is.
Here is my export excel code.
string style = #"<style> .text { mso-number-format:\#; } </style> ";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
HtmlForm frm = new HtmlForm();
...................
...................
table.RenderControl(htw);
HttpContext.Current.Response.Write(style);
//render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
While exporting to excel, adding \t before the value being inserted will solve the problem.
Eg:
string test = "000456";
string insertValueAs = "\t" + test;
The string test would then be considered as a string value and not an integer value. Thus, it would retain the leading zeros.
I have faced the same issue, and above solution worked for me. Hope this post helps!
If exporting to CSV / TSV, put this into each cell containing a textual "number" with leading 0s or (especially) 16+ digits:
="0012345"
..where 0012345 is the number you want to export to that cell.
I wish I could remember where I saw that.
In Excel file, Numbers cell always strips the leading zeros, you can set numbers with leading zeros by following a single quote. i.e.
00123450098 to '00123450098
but then, the format for that cell will changes to text.
If your generated excel file, have any formula, which is include that cell reference as number then it will not work as expected.
I had this problem as well. The solution I came up with was to sneak the leading zeros in using excel's built in char() function. In excel, char() returns the value of the ASCII character code that is passed to it, so char(048) returns 0.
Before exporting to excel, prepend your variable like so...
varName = "=CHAR(048)&" + varName;
I found my answer for this using a combination of StackOverflow link and a blog.
There are excel formatting styles that can be applied to the gridview on rowdatabound. I used those and now my export does not strip the leading zeros.
Below is an example of my code.
ExpenseResultsGrid.RowDataBound += new GridViewRowEventHandler(ExpenseResultsGrid_RowDataBound);
protected void AllQuartersGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{//add this style to prevent truncating leading zeros in fund code during export to excel
e.Row.Cells[2].Attributes.CssStyle.Add("mso-number-format", "\\#");
}
}
While exporting, just add an empty string like "" before the value that is inserted:
string x = "000123";
myWorksheet.Cells[1,1] = "" + x;

Resources