I’m using Asp.net to create a csv file that the user can open directly in excel. I want to make it possible to show the download popup and for the user to choose “Open with Excel” and that will open the file in excel.
The code to create the csv:
Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.csv", "test"));
Response.ContentType = "text/csv";
Response.Write("Year, Make, Model, Length\n1997, Ford, E350, 2.34\n2000, Mercury, Cougar, 2.38");
Response.End();
Excel needs to understand that “Year”, “Make”, etc should all be different columns. That doesn’t seem to work with the csv I’m creating, everything is just in the same column. It shows up like this:
http://oi54.tinypic.com/2evyb0k.jpg
The only way to get it working with excel is to use the “Text Import Wizard”. Then everything shows up in different columns like it should.
As I said what I need is to create a spreadsheet (it doesn’t need to be csv), it should just be easy for the user to open in excel or whatever they are using to start working with it. How would you solve this? Thanks!
Not sure why it doesn’t work like that – it does for me, but at a minimum try quoting the data:
Excel can also import XML, google “<?mso-application progid=”Excel.Sheet”?>” for the format. Or just save an excel spreadsheet as XML to see an example. Excel XML files can be named “.xls” and it will be able to open them directly.
Finally, you can use NPOI in .NET to manipulate excel spreadsheets in the native format: http://npoi.codeplex.com/
For XML you can also use a wrapper class I wrote that encapsulates this in a simple C# object model: http://snipt.org/lLok/
Here’s some pseudocode for using the class:
Or just create your own method, here are the basics.
Create the header this way:
From there, add to your output string by creating nodes using this basic structure:
Within a
<Row>, each<Cell>element creates a new column. Add a new<Row>for each spreadsheet row. TheDataTypefor<Data>can be “String” or “Number”.