Saurabh
Saurabh

Reputation: 1631

How to export to excel in windows app C#?

I am new in Windows Application development, Trying to write code for exporting dataset to excel. I have read several examples on the internet regarding this but all are exporting the file to a location. I want to export file like in web (as an open asking to save as file).
Below is my code for the web app, what changes we need to run it on a window?

DataGridView grid_records = new DataGridView();
grid_records.DataSource = dset;
//grid_records.DataBind();

Response.Clear();

Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
string FileName = "UIDAI" + DateTime.Now + ".xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
grid_records.GridLines = GridLines.Both;
grid_records.HeaderStyle.Font.Bold = true;
grid_records.RenderControl(htmltextwrtter);
Response.Write(strwritter.ToString());
//Response.End();

Response.Flush();
Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();

Upvotes: 1

Views: 12997

Answers (3)

Saurabh
Saurabh

Reputation: 1631

Thanks for so many hints , Below is my final code after converting to window app
hope it will help others

   private void btn_export_Click(object sender, EventArgs e)
    {
        try
        {
            SaveFileDialog savefile = new SaveFileDialog();
            savefile.FileName = "Response.xls";
            savefile.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
            if (dset.Tables[0].Rows.Count > 0)
            {
                if (savefile.ShowDialog() == DialogResult.OK)
                {
                    //using (StreamWriter sw = new StreamWriter(savefile.FileName))
                    //    sw.WriteLine("Hello World!");
                    StreamWriter wr = new StreamWriter(savefile.FileName);
                    for (int i = 0; i < dset.Tables[0].Columns.Count; i++)
                    {
                        wr.Write(dset.Tables[0].Columns[i].ToString().ToUpper() + "\t");
                    }

                    wr.WriteLine();

                    //write rows to excel file
                    for (int i = 0; i < (dset.Tables[0].Rows.Count); i++)
                    {
                        for (int j = 0; j < dset.Tables[0].Columns.Count; j++)
                        {
                            if (dset.Tables[0].Rows[i][j] != null)
                            {
                                wr.Write(Convert.ToString(dset.Tables[0].Rows[i][j]) + "\t");
                            }
                            else
                            {
                                wr.Write("\t");
                            }
                        }
                        //go to next line
                        wr.WriteLine();
                    }
                    //close file
                    wr.Close();
                    MetroMessageBox.Show(this, "Data saved in Excel format at location "+ savefile.FileName , "Successfully Saved", MessageBoxButtons.OK, MessageBoxIcon.Question);
                }
            }
            else
            {
                MetroMessageBox.Show(this,"Zero record to export , perform a operation first","Can't export file",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
        }
        catch (Exception ex)
        {
            MetroMessageBox.Show(this, v1.PrintExceptionDetails(ex), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            el.LogError(ex);
        }
        finally
        {

        }
    }

Upvotes: 1

udaya kumar
udaya kumar

Reputation: 291

While searching for windows desktop application related answers use keywords "Winforms","C#".

You need to select a file using SaveFileDialog class and use FileStream to write content to it.

You can find detailed samples msdn, here and here.

Upvotes: 0

M. Adeel Khalid
M. Adeel Khalid

Reputation: 1796

This example will tell you How to export Dataset to Excel, if you see the 2nd answer on this link, you'll find out how would you allow user to save the document at any location in their pc. You can open Excel file by following this link

Always search before asking a question because everything is available here whatever you'd asked.

Hope it helps!

Upvotes: 0

Related Questions