Question

Leading Zero in a CSV File

Asked by: Clif

My app creates a CSV file that the user will later double click to open it in Excel.  The CSV file contains, among other info, a couple of "numeric" text fields (zip code is one).  When the fields contain a leading zero, Excel seems to drop it.

A couple of caveats...

1. The users are, shall we say, less than tech-savvy so having them format the Excel columns every time the file is opened is out of the question.

2. The file will be opened by double clicking on it, so utilizing the Excel "text import" option is also out of the question.

3. One option I saw was to wrap the value in equals/quotes (like: ="<value>").  Excel retains this and will confuse the user if they attempted to edit the value.

Seems to me you used to be able to get around this by prepending an apostrophe, but that no longer seems to work, at least no in Excel 2003.

Any other valid options?

TIA

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-10-22 at 12:14:26ID23838319
Topic

Visual Basic Programming

Participating Experts
2
Points
50
Comments
18

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. CSV file - actually an Excel problem - losing leading zip z…
    Please excuse me for asking an Excel question, but the CSV file in question originates from Access, so of course my users consider it an Access problem. (no luck in the Excel newsgroups) I have output a mailing list from Access in CSV format (there are other reasons I'm not ...
  2. Excel file saved as csv loses leading zero in ZIP code - ho…
    Hi Experts - I have an Excel file using the Special Formatting code for ZIP Codes that allows for leading zero's in this field. However, when it is saved as a csv file (necessary for import to another company's process), it loses the leading zero - how can I preserve or rest...
  3. Getting cells value including leading apostrophe with VBA
    Hello, is there any way to get the complete value of a cell which contains a leading apostrophe with VBA? The .value property does not contain it. Thanks for you help
  4. Preserving leading zero's in a .csv file
    Hi, I am accessing a database and generating a .csv file using UNIX shell script. When i move the file to windows machine and opening the file i am loosing the leading zero's. How can i preserve this leading zero's?
  5. Suppress Leading Apostrophe
    I'm generating a csv file that the user will open with excel. The fields look like numbers but they are really text so they have leading apostrophes. These leading apostrophe's show up in the cells when the text is displayed in excel but they go away if the cell is edited by...
  6. prepend a string to an exisiting string
    I am looking to prepend 10-x #s of 0's to a string if its lenth is less than 10 and has a length x. so if I have 12345 I want to end up with 0000012345. What a short and sweet way of doing this? :) Thanks.

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: aikimarkPosted on 2008-10-22 at 13:29:11ID: 22780919

1. output your numeric text fields as quote-delimited.
2. output your data directly to an Excel file using and Excel ActiveX object.

 

by: ClifPosted on 2008-10-23 at 05:26:51ID: 22785324

1. Wrapping the numeric value in quotes doesn't appear to work.
CFI,0,"02604",20.000,G,1
CFI,0,"02604",9.890,G,2

2. I'm hoping to avoid using the Excel object, but the suggestion is duly noted

 

by: aikimarkPosted on 2008-10-23 at 05:56:14ID: 22785525

@Clif

"...doesn't appear to work"

Very interesting...and surprising that Excel doesn't get this right. :-(

The solution appears to require prepending an equal sign as shown in the snippet.

CFI,0,="02604",20.000,G,1
CFI,0,="02604",9.890,G,2

                                              
1:
2:

Select allOpen in new window

 

by: ClifPosted on 2008-10-23 at 06:02:19ID: 22785573

The problem with that is that the equals sign and quotes are then part of the text in Excel.  As I said on item #3 of the original question, should the user attempt to edit the value, seeing the equals sign and quotes would confuse them.

 

by: aikimarkPosted on 2008-10-23 at 08:03:32ID: 22786880

The snippet illustrates an old data entry trick to force numeric text to be treated as text instead of numbers.  Unfortunately, the apostrophe does show up in the cell contents.

You might replace Excel with your own application and use a spreadsheet object like the one from FarPoint.

You could create a different program to do the Excel importing.  It would need to be associated with the CSV file type.

You might create some generic workbook template that always runs an Open routine and changes the format of the third column to text.  But that will cause one of those macro virus warnings.

====================
The problem appears that the CSV importer has 'problems' or 'issues'.  :-(
The most reliable importing method is in the snippet.  I first rename the file to a non-CSV file type and then issue the .OpenText method.  This involves the least amount of Excel automation as I could generate.

CFI,0,'02604,20,G,1
CFI,0,'02604,9.89,G,2
 
 
=================================
filecopy "C:\Documents and Settings\AikiMARK\My Documents\test.csv","C:\Documents and Settings\AikiMARK\My Documents\test.csvImport"
 
Workbooks.OpenText FileName:="C:\Documents and Settings\AikiMARK\My Documents\test.csvImport", _
        StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, Comma:=True, _
        FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 2), Array(4, 1), Array(5, 1), Array(6, 1))
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

Select allOpen in new window

 

by: aikimarkPosted on 2008-10-23 at 11:57:09ID: 22789431

Please note the following:
* Using the Workbooks.OpenText method, you no longer have to use quotes around the 02604 text column.
* If you immediately performed a .SaveAs method out to the .CSV file, the user is 'editing' the CSV file with Excel.  (use overwrite and no prompt options)
* If you need to keep a more tidy directory, you should Kill the .CSVImport file.
* If you want to streamline this process further, you might save the file as .CSVImport rather than .CSV
* You can have the same icon as Excel for your application, so the user knows to double click on the file icon, assuming you have associated the .CSVImport with your ExcelImporter utility.

 

by: ClifPosted on 2008-10-30 at 12:10:18ID: 22844286

Just posting so that it's not judged an abandoned question.

Still no (viable) solution,

 

by: aikimarkPosted on 2008-10-30 at 13:04:50ID: 22844841

@Clif

What about my suggestion that you write a small applet that invokes the TextImport worksheet function?  Let's say that your program is called CSVImport.exe.  During the installation of this program, you change the registry entry for CSV file association from MSExcel.exe to CSVImport.exe.

Thereafter, your less-than-bright users see what you want them to see in the Excel worksheet and they haven't had to change their habits or learn anything new.

 

by: ClifPosted on 2008-11-03 at 05:24:06ID: 22866800

The "TextImport" applet you described would require Excel, If I could do that, I could just create the Excel file.  Unfortunately the design forbids the requirement of the user having Excel on their machine (See Caveat #2 in my original post).

 

by: aikimarkPosted on 2008-11-03 at 05:50:36ID: 22866963

@Clif

But your initial sentence assumes/requires Excel be on the user PC
"the user will later double click to open it in Excel"

 

by: ClifPosted on 2008-11-03 at 05:58:16ID: 22866999

For those customers who have Excel, which some do and some don't.

 

by: aikimarkPosted on 2008-11-03 at 06:29:29ID: 22867246

What should your Excel-less customers see when they double-click on the .CSV file?

In general, you can distribute the importer utility along with your application.  During setup, you can detect whether Excel is installed on the PC and then associate the CSV file type with your imported utility.

If you have some naming standard with your output routine, you can change the importer to do its magic when the file matches the pattern or pass it directly to Excel/Notepad (whatever is defined at the time of installation) if it doesn't match the pattern.

 

by: ClifPosted on 2008-11-03 at 06:47:34ID: 22867361

It doesn't matter what Excel-less people see.

I'm sorry of I sound a little snarky, but I have specific requirements that must be met.  These requirements were posted in my initial question so it's not as if I'm changing them just to avoid grding the question.  The reason that these requirements exist is my own business, suffice it to say that they do exist and are unchangeable.

 

by: aikimarkPosted on 2008-11-03 at 07:02:51ID: 22867494

I don't mind the snark as long as we are communicating.  Other EE experts may disagree.
1. The only way to format the CSV file to correctly import into Excel would be to prepend the columns with an apostrophe character.  It still works.  However, there are two problems:
  * the users will see the apostrophe in Excel and in any other application, such as Notepad.
  * if the user removes the leading apostrophe, Excel will strip the leading zeroes.
  * Even if the CSV is successfully imported into Excel with the leading zeroes and no prepended apostrophe, the cell may be automatically converted to numeric by Excel if the user edits the cell, whether that edit removes leading zeroes or not.

2. I'm working within your requirements.

3. The solution is to create an ExcelCSV importer applet that is installed, along with the main application, on your users' PCs.  The importer applet can intelligently (selectively) do the import into Excel or not.

"The reason that these requirements exist is my own business..."
4. I'm not challenging your requirements.  There *does* seem to be an inconsistency between your double-click-to-open-within-Excel action and your later statement that seems to drop the condition/requirement that Excel is installed on your users' PCs.

5. Your requirements don't address the problem of Excel changing a leading zero text cell to a numeric cell automatically.

 

by: ClifPosted on 2008-11-03 at 07:25:34ID: 22867704

1. There in lies the problem and the reason I asked the question.

2. No, you keep asking me to create an app that requires the existence of Excel.

3. I am not allowed to create an app or applet that requires the user have Excel installed.

4. The inconsistency is only if you refuse to consider the possibility that their will be more than one machine available.  In reality, those that do not have Excel locally will be emailing the CSV file to another department (who do not want a Text Import applet)

5.  Again, this is the problem.  At one point many years ago, an apostrophe prepended to a value forced Excel to format that value as text.  It no longer does this, I was wondering if Microsoft had changed it from an apostrophe to something else.

 

by: aikimarkPosted on 2008-11-03 at 07:52:49ID: 22867978

5. I just verified that the leading apostrophe trick still works with Excel2003.  You can force data to be treated as text by starting the column data with an apostrophe.
Note: The user will see the apostrophe in the cell contents.

2 & 3 & 4. I'm not suggesting that creating and distributing an importing applet along with your application requires the presence of Excel.  

* * * IF, AND ONLY IF, the user has Excel would your applet be used * * *

If any of your users does NOT have Excel, they will not use your applet.  They won't even know it exists.

===============
6. It is *YOUR APPLICATION* that creates a CSV file.  If *some* users have a problem when they double-click on the file icon, my recommendation addresses that subset of your users.  I am not suggesting anything that would affect any non-Excel users.

7. I am *NOT* trying to change your requirements and constraints.  

8. You could create an applet that displays the candidate CSV files to the user and opens the selected file with the appropriate application (Notepad, Excel).  The user does not need to see the raw CSV file in an Explorer window, just the list your applet displays.

9. Unless you add more user-related constraints (installation, distribution, authority, etc.) I can only suggest that you have enough to solve the problem as you've described it.

10. The points aren't as important as solving problems.  However, it is incumbent upon you to adequately describe the problem and all the constraints.  I suspect that we are still having this discussion because you have not disclosed something that is very important.

 

by: WRNewmanPosted on 2010-02-09 at 05:09:35ID: 26523637

There are many tools that create csv files but the actual structure is often sloppy
To be sure of your file create it yourself

Open "myfile,csv" for out put as #1

The big problem in writing csv files is the separator itself and the quotes needed so if you want
1,"text",2.768,"more text" you can do it using ascii characters 44 is a comma 34 is double quotes
so
print #1, "1"+chr(44)+chr(34)+"text"+chr(34)+chr(44)+"2.768"+chr(44)+chr(34)+"more text"

will do the trick. It works because the data is embedded in the string by removing VB's own " quotes and inserts 1 into the output string, it then adds a comma from the chr(44) then the quotes needed by the CSV rules from the chr(34) then removes the quotes the text and inserts that followed by another set of quotes from the chr(34) etc

Using this method absolutely guarantees that the CSV format you want is what you get.
Sorry the answer is a bit late, have not been around here for a long time.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...