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;
Related
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
I am trying to read a cell with possible trailing zeros as a string instead of numeric (which strips off leading zeros). The cell is read by integer column/row as below instead of column string as this answer has.
initial code
$instReader = $reader->load($this->file);
$sheet = $instReader->getSheet(0);
I tried modifying this from:
$keyCell = $sheet->getCellByColumnAndRow(1,5);
to:
$sheet->setCellValueExplicitByColumnAndRow(1,5, PHPExcel_Cell_DataType::TYPE_STRING);
$keyCell = $sheet->getCellByColumnAndRow(1,5);
the former gives 1407 for $keyCell instead of 01407
the latter gives "s" or ""
how do I treat the cell as string before calling getCellByColumnAndRow and using only integer values for column and row.
(BTW, if this can be done once for an entire column instead of each time for each individual cell that would be better)
$keyCell = $sheet->getCellByColumnAndRow(1,5)->getValue();
Will read the cell data in the format that it's actually stored by Excel, you can't arbitrarily change that or tell PHPExcel to read it as a different datatype.
However, if the cell has formatting applied, then you can use
$keyCell = $sheet->getCellByColumnAndRow(1,5)->getFormattedValue();
instead, and this will return the data as a string, with whatever format mask was defined in the Excel spreadsheet
Same issue for me. I become crazy.
Tried to set
$objReader->setReadDataOnly(true);
wasn't working
tried
$sheet->getCellByColumnAndRow(4,$row)->getValue()
because normaly display text as raw => doesn't working.
So last I change code in library. Edit file named DefaultValueBinder.php
Search for dataTypeForValue function and set this :
} elseif (is_float($pValue) || is_int($pValue)) {
return PHPExcel_Cell_DataType::TYPE_STRING;//TYPE_NUMERIC patch here;
} elseif (preg_match('/^\-?([0-9]+\\.?[0-9]*|[0-9]*\\.?[0-9]+)$/', $pValue)) {
return PHPExcel_Cell_DataType::TYPE_STRING;//TYPE_NUMERIC patch here;
So now return numbers with 0
I am want to read excel file having phone numbers stored as numbers but when I read the file using SheetJS/js-xlsx (npm install xlsx), All the large phone numbers are converted to strings like
9.19972E+11
919971692474 --> 9.19972E+11
My code is
var workbook = XLSX.readFile(req.files.fileName.path);
var sheet_name_list = workbook.SheetNames;
var csvFile = XLSX.utils.sheet_to_csv(workbook.Sheets[sheet_name_list[0]]);
console.log(csvFile2);
console output is
customer_phone,product_name
9.19972E+13,"Red Belly Shoes,"
Is there any way I can avoid such conversion?
The number 919971692474 is normally displayed as 9.19972E+11 in Excel. To force it to display the full number you have to set the number format to 0 (right click, format cell, choose custom type '0'). And when you do that, the full number is displayed. If you don't set a format in excel, the xlsx module uses the "General" format and that number format displays the phone number as an exponential.
If the file is incorrect, you can override the CSV formatting by deleting the w key and adding a z key corresponding to the desired number format. For example, to change cell A2:
var sheet = workbook.Sheets[workbook.SheetNames[0]];
delete sheet.A2.w;
sheet.A2.z = '0';
If you want to do this for all number cells, just loop:
Object.keys(sheet).forEach(function(s) {
if(sheet[s].w) {
delete sheet[s].w;
sheet[s].z = '0';
}
});
By default sheet_to_csv take the formatted numbers.
- To avoid the formatted value and to take raw inputs (original values) you have to add parameter in sheet_to_csv method you have to set rawNumbers to true
Try this code
var csvFile = XLSX.utils.sheet_to_csv(workbook.Sheets[sheet_name_list[0]], { rawNumbers: true });
It seems in later versions w is not there. That's how it could be done in recent versions.
const ws = XLSX.utils.json_to_sheet(data);
Object.keys(ws).forEach(function(s) {
if(ws[s].t === 'n') {
ws[s].z = '0';
ws[s].t = 's';
}
});
const csv = XLSX.utils.sheet_to_csv(ws);
Using sheet[s].z = '0'; works in removing the scientific notation, but it also removes any decimal places you might want to retain. From the readme:
The cell.w formatted text for each cell is produced from cell.v and cell.z format.
I was able to remove the scientific notation by explicitly setting the value of w instead of letting xlsx calculate it for me:
if (cell.t === 'n') {
cell.w = cell.v;
}
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).
I've got the value '9,2' (dutch notation of '9.2') within a cell of a .xlsx file, the cell has a 'general' number format. Also the value in the upper bar where you also view formulas says '9,2' When I read this cell with PHPExcel with ->getValue() I get '9,199999999999999'.
This is my code:
$oPhpReader = PHPExcel_IOFactory::createReader($sFileType);
$aWorksheetNames = $oPhpReader->listWorksheetNames($sFileName);
$oPhpReader->setReadDataOnly(true);
$oPhpReader->setLoadSheetsOnly($aWorksheetNames[0]);
$oPhpExcel = $oPhpReader->load($sFileName);
$oWorksheet = $oPhpExcel->getActiveSheet();
$oCell = $oWorksheet->getCellByColumnAndRow($iCol,$iRow);
$sTempValue = $oCell->getValue();
This is the way I solved my problem now. Though I do not think this is a very neat solution, it is probably the only way.
I just figured I will never get numbers with more than 12 digits, only when PHPExcel get them wrong. So I round all my floats to 12 digit using number_format:
if ((is_numeric($sTempValue))&&(strpos($sTempValue,'.')))
{
$sTempValue = rtrim(rtrim(number_format($sTempValue,12,',',''),'0'),',');
}