c# - 如何在 C# Windows 应用程序中将数据表导出到 Excel

标签 c# mysql excel

<分区>

我通过谷歌搜索找到了一些代码,允许我将数据表导出到 excel 文件。我成功地从数据库表中导出文件并将其保存在我的文档中 我的编码是:

  using System;
  using System.Data.OleDb;
  using System.Windows.Forms;
  using MySql.Data.MySqlClient;
  using System.Data;

namespace ImportFile

{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    String connection = "SERVER=******;"DATABASE=dbd;"UID=root;"PASSWORD=pws;"Convert Zero Datetime = True";
 private void BExport_Click(object sender, EventArgs e)
    {
        DateTime dat = DateTime.Now;
        int time = dat.Hour;
        int time1 = dat.Minute;
        int time2 = dat.Second;
        int month = dat.Month;
        int day = dat.Day;
        MySqlConnection connection1 = new MySqlConnection(connection);
        connection1.Open();
        MySqlCommand command = new MySqlCommand ("SELECT * FROM TABLE_Name",connection1);     
        MySqlDataAdapter dataadpter = new MySqlDataAdapter(command);
        DataTable datatable = new DataTable("TABLE_NAME");
        dataadpter.Fill(datatable);
        datatable.WriteXml("C:\\Users\\Downloads\\agent.xlsx" + time + " - " + time1 + " - " + time2 + " - " + day + " - " + month + "");
        MessageBox.Show("export data");

      }
     }
   }

我的问题是,当我下载文件(点击导入按钮)时,它下载的不是 excel 文件,它只是一个普通文件

我如何将其下载为 excel 文件 。如果有人知道这个.... 帮助我

最佳答案

这一行是一个问题:

datatable.WriteXml("C:\\Users\\Downloads\\agent.xlsx" + time + " - " + time1 + " - " + time2 + " - " + day + " - " + month + "");

您编写了 agent.xlsx,但随后在末尾添加了一些其他值。

第二个问题就像Lewis Hai 已经描述的一样in his answer , 是您正在使用 WriteXml 方法,该方法会将您的数据写入 XML。

关于c# - 如何在 C# Windows 应用程序中将数据表导出到 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34350785/

相关文章:

mysql - 无法在 MySql 中添加外键

excel - 数据透视表根据值的计数计算字段

C# linq order by 和其他带有 foreach 的语句,是否存在性能差异?

c# - 在 Silverlight 中的运行时创建一个 ControlTemplate

c# - 取消引用可能的空引用 C#

excel - 有没有办法限制使用 VBA 删除工作表中的行?

Excel – 使用 VB 脚本生成 Word 文档

c# - 在 Safari 浏览器上使用 Selenium Webdriver 未选择下拉列表

mySQL - 1067 - 'updated_at' 的默认值无效

php - 检查 mysql_connect() 是否失败?