Sql script display leading 0 in excel output file - excel

I have sql script "example.sql": SPOOL &1 Select '<.TR>'||'<.TD align="left">'||column_name||'<./TD>'||'<.TR>' from table1; spool off..which dumps it contents to cshell script "getdata.csh" this is how i get data from sql script to csh script sqlplus $ORA_UID/$ORA_PSWD #${SQL}example.sql ${DATA}${ext} once i extract data from it i create a excel file by combining 3 files header. html <html>
<.head>
<.title)
Title
<./title>
<./head>
<.body>
<.table >
<.tr>
<.th>Column Name<./th>
<.tr>ext file that has query results and trailer.html <./tr>
<./table>
<./body>
<./html> and i save this file as .xls and send it through email as attachment.. Now my problem is Column_name has data that starts with 0 but when i open excel file leading 0 are gone but i wanna keep that 0.. so what can i add to make sure that email attached excel file will have leading 0 when that is opened on the other side.. plz any help would be good

Using oracle:
Say your attribute is called 'number'
select '0' || to_char(number) as number
from table mytable

Use the excel object model, or a macro to go into the excel file grab the column and change the formatting.
In your case:
Range("A1").Numberformat = "#"

If you're generating the excel file on the fly, you could prepend those numbers with an apostrophe, ie '
This causes Excel to treat the number like a string. The only downside is it might cause some side effects if the sheet has any equations that use those numbers.

I have dealt with this issue in the past, and the problem is strictly a "feature" of Excel formatting. Unfortunately, I don't have the resources to completely test an answer, but here are two things you can try.
Add a step inside your cshell script to surround your $1 value with ="",
awk '{$1= "=\"" $1 "\""; print $0}' inFile > outFile
The downside is that you're now telling Excel to treat these values as strings. If you're doing any fancy calculations on these values you may have different problems.
#2 (why does SO formatting always renumber numbered blocks as 1 !;-!) . As this is really an Excel formatting problem AND in my recollection, you can't retrieve the leading zero once the file has been opened and processed, I seem to remember I had a trick of pre-formatting a black worksheet, saving it as a template, and then loading the file into the template. I recall that was tricky too, so don't expect it to work. You might have to consult Excel users on the best tactics if #1 above doesn't work.
You might also want to tell people what version of Excel you are using, if you go to them for help.
I hope this helps.
P.S. as you appear to be a new user, if you get an answer that helps you please remember to mark it as accepted, and/or give it a + (or -) as a useful answer

Related

office 365 excel csv hyperlink not displaying correctly when imported to excel [duplicate]

Can Excel interpret the URLs in my CSV as hyperlinks? If so, how?
You can actually do this and have Excel show a clickable link. Use this format in the CSV file:
=HYPERLINK("URL")
So the CSV would look like:
1,23.4,=HYPERLINK("http://www.google.com")
However, I'm trying to get some links with commas in them to work properly and it doesn't look like there's a way to escape them and still have Excel make the link clickable.
Does anyone know how?
With embedding the hyperlink function you need to watch the quotes. Below is an example of a CSV file created that lists an error and a link to view the documentation on the method that failed. (Bit esoteric but that's what I am working on)
"Details","Failing Method (click to view)"
"Method failed","=HYPERLINK(""http://some_url_with_documentation"",""Method_name"")"
I read all of these answers and some others but it still took a while to work it out in Excel 2014.
The result in the csv should look like this
"=HYPERLINK(""http://www.Google.com"",""Google"")"
Note: If you are trying to set this from MSSQL server then
'"=HYPERLINK(""http://www.' + baseurl + '.com"",""' + baseurl + '"")"' AS url
you can URL Encode your commas inside the URL so the URL is not split across multiple cells.
Just replace commas with %2c
http://www.xyz.com/file,comma.pdf
becomes
=hyperlink("http://www.xyz.com/file%2ccomma.pdf")
Yes, but it's not possible to link them automatically. CSV files are just text files - whatever opens and reads them is responsible for allowing you to click the link.
As to how Excel seems to handle CSV files - everything between commas is interpreted as if it already had been typed into the cell. Therefore, the CSV file containing ="http://google.com",=A1 will display as http://google.com,http://google.com in Excel. It's important to note, however, that hyperlinks in Excel are metadata, and not the result of anything in the actual cell (ie, a hyperlinked cell to Google still contains http://google.com not <a>http://google.com</a> or anything of that sort.)
Since that's the case, and all metadata is lost when converting to a CSV, it's impossible to tell Excel you wish for something to be hyperlinked merely by changing the cell value. Normally, Excel interprets your input when you hit 'Enter' and links URLs then, but since CSV data is not being entered, but rather already exists, this does not happen.
Your best bet is to write some sort of addon or macro to run when you open up a CSV which parses every cell and hyperlinks them if they match a URL format.
Use this format:
=HYPERLINK(""<URL>"";""<LABEL>"")
e.g.:
=HYPERLINK(""http://stackoverflow.com"";""I love stackoverflow!"")
P.S. The same format works in LibreOffice Calc as well.
"=HYPERLINK(\"\" " + "http://www.mywebsite.com"+ "\"\")"
use this format before writing to CSV.
As described above, "=HYPERLINK(""http://www.google.com"", ""Google"")" is what worked for me.
However, In Excel Version 2204 Click to Run, I couldn't have leading white space.
For example;
FirstName, "=HYPERLINK(""http://www.google.com"", ""Google"")" fails
FirstName,"=HYPERLINK(""http://www.google.com"", ""Google"")" success
The issue here for me was that because a .CSV by it's nature is Comma separated, any commas in the text file are interpreted as separators. It worked for me by using tab characters as separators, saving it as a .TXT file so that when opened in EXCEL you choose the TAB character rather than ','.
In the text file …
## ensure that the file is TAB separated
Item 1 A file Name data.txt
Item 2 Col 2 =HYPERLINK("http:\www.ilexuk.com","ILEX")
"ILEX" then is shown in the cell and "http:\www.ilexuk.com" is the hyperlink for the cell.

ssrs report export to excel - broken hyperlinks

I have large report and each row contains hyperlink.
Report containing 50k or more rows is exported to excel.
After export I try to open xlsx file and get message telling me that file contains error. It also suggests to do file recovery
After recovery message shows that hyperlinks were removed. I can open file but links are no longer working.
I tried to open exported file with c# openxml sdk library and got error message telling that file contains incomplete element but i was unable to find which element it is
However, when report has less than 49k rows, exported file is opened succesfully and all hyperlinks are working.
When report is exported to pdf or doc, hyperlinks are also working
I use report server vesion 12.0.2269.0
Does anyone know how to resolve this issue ?
Usually, when I have experienced this sort of issue after an Excel file exported from SSRS, I find there is something in the data that Excel has issue with. A hidden character, perhaps. The export works, opening the file is when the problem starts.
To deal with this situation I created a user defined function (UDF) in SQL Server to remove any characters that I know Excel will choke on. Below is an example of one I use.
CREATE FUNCTION [dbo].[udf_CleanData]
(
#data text
)
RETURNS varchar(max)
AS
BEGIN
DECLARE #cdata varchar(max) = #data
SELECT #cdata = REPLACE(#cdata, char(20), '') -- double quote
SELECT #cdata = REPLACE(#cdata, char(21), '') -- bullet
SELECT #cdata = REPLACE(#cdata, char(13), '') -- carriage return
SELECT #cdata = REPLACE(#cdata, char(10), '') -- line feed
SELECT #cdata = REPLACE(#cdata, char(18), '') -- single quote right
SELECT #cdata = REPLACE(#cdata, char(17), '') -- single quote left
SELECT #cdata = REPLACE(#cdata, char(22), '') -- dash
RETURN #cdata
END
You can adjust this any way you want to meet your need. This works for what I need, and that is removing all the strange characters in a text field that the dev team thought would be good to use for formatting on the front end application.
Usage:
SELECT dbo.udf_CleanData(Field1) AS CleanField1 FROM Table1
If the hyperlink you are reporting has anything unusual in it, this might remove that. If you are building the hyperlink from various pieces of data, some or all of the fields may need to be scrubbed. This is something where you will have to go through a bit of trial and error.
Other times when I have had this issue, there is an expression in the RDL that ends up calculating to either NaN, or Infinity. The Excel file after export seems to have issue with this except when exporting to an older version of Excel, like 2003.
The best way to handle this situation is adjust your expressions to check for the possibility that the final value could be out of whack, and default the value to something else, or round the value to something reasonable. This is similar to checking that a denominator is not zero before doing division.
=IIf(Fields!Total.Value > 0, Fields!Count.Value/Fields!Total.Value, 0)
There are plenty of questions about this type of thing with good solutions here on SO, so I won't list a bunch of expressions here related to data checking.
The other way to handle this is to always export to an earlier version of Excel, but that may not be any easy option, or an option at all. Usually, I only see that as an option on a report subscription, but not in the development tools.
Good luck to you!
I have also faced this issue when exporting SSRS reports to Excel. The reason in my case was that Excel can only handle 66530 hyperlinks -
https://support.office.com/en-us/article/Excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3#ID0EBABAAA=2016,_2013
Confirm again if you get this issue the moment you go over 50k (in which case the reason could be what R Richards suggests), or if it is 66530 links that cause the spreadsheet to break.
I havent found a way get around this limitation of Excel, so the only way I can think of to resolve this is to not have hyperlinks in the exported excel file at all.
If you can live without hyperlinks in the exported file, you can disable them in the report using the Globals!RenderFormat property of the SSRS report. The expression to use on the cells to not have hyperlinks if the requested format is EXCEL would be -
=IIF(Globals!RenderFormat.Name="EXCELOPENXML" ,True,False)

Looking up multiple values in a list

I'm trying to select multiple values based on a search key. In it's most basic form there is no problem with this. I followed this example and everything went well:
http://office.microsoft.com/en-us/excel-help/how-to-look-up-a-value-in-a-list-and-return-multiple-corresponding-values-HA001226038.aspx
=IF(ISERROR(INDEX($A$1:$B$7,SMALL(IF($A$1:$A$7=$A$10,ROW($A$1:$A$7)),ROW(1:1)),2)),"",INDEX($A$1:$B$7,SMALL(IF($A$1:$A$7=$A$10,ROW($A$1:$A$7)),ROW(1:1)),2))
The problem with this however is that in my case I have multiple CSV files (external) where some values in my A$ column look like this:
=- sometext // results into #NAME? error
Excel interprets these as a formulas where it is actually only supposed to be a string. Sure I could change it to text and save it again but I would like to avoid any manipulation in these CSV files.
I tried to extend the second IF statement (if you read it from left to right) with:
IF(AND($A$1:$A$7 <> "#NAME?", $A$1:$A$7=$A$10,ROW($A$1:$A$7)))
and
IF(AND(NOT(ISERROR($A$1:$A$7)), $A$1:$A$7=$A$10,ROW($A$1:$A$7)))
Both didn't work. (Sorry if I messed up some syntax and formula names, I'm using a different language version)
Here a small image of what's happening right now and how it should look:
On the right site you can see a list of values right next to Test1 which are missing on the left site due to the #NAME? error.
I would suggest opening the csv's files as text files. Selecting Comma as your delimiter and then select Text as your Column data format. This way, Excel will treat all your data as text and will not try to read =- sometext as a formula.
To do so, you would need to change your .csv files extension to .txt or anything else (even no file format).
Instead of "Opening" the CSV file, you can "Import" it. This will open the Text Import Wizard which will allow you to specify particular columns as Text. This is located in different areas in different versions of Excel. In Excel 2007, it is on the Data Tab / Get External Data / From Text. The example below demonstrates bringing in long numbers, but it should work just as well with your formula "lookalikes"

Excel - Variable number of leading zeros in variable length numbers?

The format of our member numbers has changed several times over the years, such that 00008, 9538, 746, 0746, 00746, 100125, and various other permutations are valid, unique and need to be retained. Exporting from our database into the custom Excel template needed for a mass update strips the leading zeros, such that 00746 and 0746 are all truncated to 746.
Inserting the apostrophe trick, or formatting as text, does not work in our case, since the data seems to be already altered by the time we open it in Excel. Formatting as zip won't work since we have valid numbers less than five digits in length that cannot have zeros added to them. And I am not having any luck with "custom" formatting as that seems to require either adding the same number of leading zeros to a number, or adding enough zeros to every number to make them all the same length.
Any clues? I wish there was some way to set Excel to just take what it's given and leave it alone, but that does not seem to be the case! I would appreciate any suggestions or advice. Thank you all very much in advance!
UPDATE - thanks everybody for your help! Here are some more specifics. We are using a 3rd party membership management app -- we cannot access the database directly, we need to use their "query builder" tool to get the data we want to mass update. Then we export using their "template" format, which is called XLSX but there must be something going on behind the scenes, because if we try to import a regular old Excel, we get an error. Only their template works.
The data is formatted okay in the database, because all of the numbers show correctly in the web-based management tool. Also, if I export to CSV, save it as a .txt and import it into Excel, the numbers show fine.
What I have done is similar to ooo's explanation below -- I exported the template with the incorrect numbers, then exported as CSV/txt, and copied / pasted THOSE numbers into the template and re-imported. I did not get an error, which is something I guess, but I will not be able to find out if it was successful until after midnight! :-(
Assuming the data is not corrupt in the database, then try and export from the database to a csv or text file.
The following can then be done to ensure the import is formatted correctly
Text file with comma delimiter:
In Excel Data/From text and selected Delimited, then next
In step 3 of the import wizard. For each column/field you want as text, highlight the column and select Text
The data should then be placed as text and retain leading zeros.
Again, all of this assumes the database contains non-corrupt data and you are able to export a simple text or csv file. It also assumes you have Excel 2010 but it can be done with minor variation across all versions.
Hopefully, #ooo's answer works for you. I'm providing another answer mainly for informational purposes, and don't feel like dealing with the constraints on comments.
One thing to understand is that Excel is very aggressive about treating "numeric-looking" data as actual numbers. If you were to open the CSV by double-clicking and letting Excel do its thing (rather than using ooo's careful procedure), those numbers would still have come up as numbers (no leading zeros). As you've found, one way to counteract this is to append clearly nonnumeric characters onto your data (before Excel gets its grubby hands on it), to really convince Excel that what it's dealing with is text.
Now, if the thing that uploads to their software is a file ending in .xlsx, then most likely it is the current Excel format (a compressed XML document, used by Excel 2007 and later). I suppose by "regular old Excel" you mean .xls (which still works with the newer Excels in "compatibility mode").
So in case what you've tried so far doesn't work, there are still avenues to explore before resorting to appending characters to the end of your data. (I'll update this answer as needed.)
You're on the right track with the apostrophe.
You'll need to store your numbers in excel as text at the time they are added to the file.
What are you using to create the original excel file / export from database?
This will likely be where your focus needs to be regarding your export.
For example one approach is that you could potentially modify the database export to include the ' symbol prefix before the numbers so that excel will know to display them as text.
I use the formula =text(cell,"# of zeros of the field") to add preceding zeros.
Example, Cell C2 has 12345 and I need it to be 10 characters long. I would put =text(c2,"0000000000").
The result will be 0000012345.

CSV Exporting: Preserving leading zeros

I'm working on a .NET application which exports CSV files to open in Excel and I'm having a problem with preserving leading zeros when the file is opened in Excel. I've used the method mentioned at http://creativyst.com/Doc/Articles/CSV/CSV01.htm#CSVAndExcel
This works great until the user decides to save the CSV file within Excel. If the file is opened again in Excel then the leading zeros are lost.
Is there anything I can do when generating the CSV file to prevent this from happening.
This is not a CSV issue.
This is Excel loving to play with CSV files.
Change the extension to something else.
As #GSerg mentions, this is not a CSV issue.
If your users must edit/save in Excel they need to select the entire worksheet, right-click and choose "Format Cells" and from the Category list select "Text" after opening the csv file. This will preserve the leading zeros since the numbers will be treated as simple text.
Alternatively, you could use Open XML SDK 2.0, or some other Excel library, to create an xlsx file from your csv data and programmaticaly set the Cell type to Text in order to take the end users out of the equation...
I found a nice way around this, if you add a space anywhere along the phone number, the cell is then not treated as number and is treated as a text cell in both Excel and Apple's iWork Numbers.
It's the only solution I've found so far that plays nice with Numbers.
Yes I realise the number then has a space, but this is easy to process out of large chunks of data, you just have to select a column and remove all spaces.
Also, if this is web related, most web type things are ok with users entering a space in the number field. E.g you can tap-to-call on mobiles.
The challenge is to get the space in there in the first place.
In use:
01202123456 = 1202123456
but
01202 123456 = 01202 123456
Ok, new discovery.
Using Quick Preview on Mac to view a CSV file the telephone column will display perfectly, but opening the file fully with Numbers or Excel will ruin that column.
On some level Mac OS X is capable of handling that column correctly with no user meddling.
I am now working on the best/easiest way to make a website output a universally accepted CSV with telephone numbers preserved.
But maybe with that info someone else has an idea on how to make Numbers handle the file in the same way that Quick Preview does?

Resources