Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Export datatable to excel format issues

Posted on 2010-09-23
8
896 Views
Last Modified: 2013-12-16
I have a small code snippet to export my data in the datatable to a generic spreadsheet.  I want to format the spreadsheet so that column names clear, reduce font size to 10, but I am not sure how to do this in my current code.  I thought I could use Stringbuilder's appendformat property or insert, but this is not clear to me.  Please advise.
private void exportToExcel()
    {
        string postdate = Convert.ToString(DateTime.Now.ToString("MMddyy_hhmmsstt"));
        string dirName = @"C:\AvReport\";
        string strFilePath = "AVInventory_" + postdate + ".csv";
        DirectoryInfo dInfo = new DirectoryInfo(dirName);

        StringBuilder sb = new StringBuilder();

        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "";
        Response.ContentType = "application/excel";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + strFilePath);

        if (!dInfo.Exists)
            dInfo.Create();         
      
        DataTable dt = new DataTable();
        
        string mc = ConfigurationManager.ConnectionStrings["SiteDB"].ConnectionString;

        using (SqlConnection conn = new SqlConnection(mc))
        {
            conn.Open();

            using (SqlDataAdapter ada = new SqlDataAdapter("SELECT * from shwAll", conn))
            {
                ada.Fill(dt);

                //column names
                for (int k = 0; k < dt.Columns.Count; k++)
                {
                    sb.Append(dt.Columns[k].ColumnName + ',');                    
                }

                sb.Append("\r\n");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    for (int k = 0; k < dt.Columns.Count; k++)
                    {
                        sb.Append(dt.Rows[i][k].ToString().Replace(",", ";") + ',');
                    }
                    sb.Append("\r\n");
                }

                Response.Write(sb.ToString());
                Response.Flush();   
                Response.End();    
          
            }        

            lblconfirmation.Visible = true;
           lblconfirmation.Text = "<span class='alert'>The file <u>" + strFilePath + "</u> was successfully saved!</span>";

        }
    }

Open in new window

0
Comment
Question by:ayoZen
  • 5
  • 3
8 Comments
 
LVL 16

Expert Comment

by:kris_per
ID: 33745492

You are sending the csv data to the response. You can not keep the excel cell/font formattings in csv file.

You have to create .xls file and then read the data of xls file and write that data in response.

To create .xls file first, you can use:
Excel interop => http://msdn.microsoft.com/en-us/library/ms173186(VS.80).aspx

OR ado.net => http://support.microsoft.com/kb/316934
http://www.davidhayden.com/blog/dave/archive/2006/05/26/2973.aspx


0
 

Author Comment

by:ayoZen
ID: 33745628
Hello Kris_per.  Thanks for your reply.  I opted not to use the Excel Interop, as the production server doesn't have excel installed, nor will the network group add it to that server.  Are there any other options for formatting?
0
 
LVL 16

Expert Comment

by:kris_per
ID: 33745747

The other option is to use ADO.NET (ole db driver) to create excel files...
http://support.microsoft.com/kb/316934
http://www.davidhayden.com/blog/dave/archive/2006/05/26/2973.aspx

Though I am not sure if font/formatting details can be set using ado.net...

One thought is to have a template xls file which are already formatted with proper size/font, etc...and then using ado.net (above links) export the data to appropriate cells and then write the .xls file data to response...
0
How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

 
LVL 16

Expert Comment

by:kris_per
ID: 33745773

There are some 3rd party libraries to create xls file without using excel interop like Aspose => http://www.aspose.com/categories/.net-components/aspose.cells-for-.net/default.aspx
0
 

Author Comment

by:ayoZen
ID: 33746564
the file will be generated daily and the user wants to be able to archive the files.  We can't use the 3rd party, but you mentioned the following:

<<One thought is to have a template xls file which are already formatted with proper size/font, etc...and then using ado.net (above links) export the data to appropriate cells and then write the .xls file data to response...>>

could this template be created everytime the user needs it?
0
 
LVL 16

Accepted Solution

by:
kris_per earned 500 total points
ID: 33747348

Create an excel file in ms excel in another machine where ms excel is installed.
In Sheet2 copy some temporary data without any formatting (Sheet2 will be just a data-holder)
In Sheet1 format the cells, like heading with big font, thick borders, etc; for the data refer to the cells of Sheet2 using formula. So when you change the data in Sheet2, values in Sheet1 also will change, but the format will remain the same.
Copy this template file (say AVInventory_template.xls) to the production server in a folder (could be web app's App_Data folder).
When exporting using ado.net(oledb driver), copy this template file to another file with a unique file name so that multiple user requests at the same time will not cross-over the same file. Export the data to Sheet2 of the uniquely named template file (dont touch Sheet1 so formatting will not be disturbed).
After exporting, read the data from the file and write to response.

This is just my thought and I hope it will work.

0
 
LVL 16

Expert Comment

by:kris_per
ID: 33747401

Just remembered your notes on 'daily generation and archiving'. That wouldn't be an issue. Instead of making a unique file name for every request, you can name the exported file with current date. When a request comes, it can look for the file name having today's date. If it is already there, it will not do export and it will just read and write to response. If it is not there, then it can export first, (may be copy it to another archive folder) and then send to response. Any subsequest requests will use that file.
0
 

Author Closing Comment

by:ayoZen
ID: 33757397
The expert provided a great alternative to my problem!  Thank you again!
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question