如何在 windows 应用程序 C# 中导出到 excel?

How to export to excel in windows app C#?

我是 Windows 应用程序开发的新手,正在尝试编写将数据集导出到 excel 的代码。我已经在互联网上阅读了几个关于此的示例,但所有示例都将文件导出到某个位置。我想像在 web 中一样导出文件(作为一个打开要求另存为文件)。
下面是我的网络应用程序代码,我们需要 运行 它在 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();

这个例子会告诉你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

提问前一定要先搜索,因为无论你问什么,这里都有。

希望对您有所帮助!

在搜索 windows 桌面应用程序相关答案时使用关键字 "Winforms"、"C#"。

您需要使用 SaveFileDialog class select 一个文件并使用 FileStream 向其写入内容。

您可以找到详细的示例 msdn, here and here

感谢这么多提示,下面是我转换为 window 应用程序后的最终代码
希望它能帮助别人

   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
        {

        }
    }