使用C#将SQL Server数据导出到Excel?

使用C#将SQL Server数据导出到Excel?,c#,sql,excel,export-to-excel,C#,Sql,Excel,Export To Excel,我和一位同事正在进行一项任务,该任务要求将SQL服务器的数据传输到MS Excel;使用C#。我能够开发出我认为有效的“基础”,但我无法运行该程序。感谢您的帮助 namespace ProjectLab1 { class Program { protected void page_load(object sender, EventArgs e) { } protected void btnExport_Click(object sender,

我和一位同事正在进行一项任务,该任务要求将SQL服务器的数据传输到MS Excel;使用C#。我能够开发出我认为有效的“基础”,但我无法运行该程序。感谢您的帮助

namespace ProjectLab1
{ 
    class Program
    {
    protected void page_load(object sender, EventArgs e)
    {

    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        string strDelimiter = ddlExportFormat.SelectedValue == "COMMA DELIMITED" ? " ," : "|";
        string conString = "Driver={MySQL ODBC 5.3 ANSI Driver};"
           + "Server=****;Port=****;"
           + "Database=****;"
           + "uid=***;pwd=****";
        StringBuilder sb = new StringBuilder();
        using (OdbcConnection connection = new OdbcConnection(conString))
            connection.Open();
        {
            string theQuery = "SELECT * FROM item i, inventory v where i.invent_id=v.invent_id";
            OdbcDataAdapter DataAdapter = new OdbcDataAdapter(theQuery, connection);
            DataSet ds = new DataSet();
            DataAdapter.Fill(ds, "items");

            ds.Tables[0].TableName = "ITEM";
            ds.Tables[1].TableName = "QUANT";
            ds.Tables[2].TableName = "SIZE";
            ds.Tables[3].TableName = "COLOR";
            ds.Tables[4].TableName = "PRICE\n";

        }

        foreach (DataRow itemDR in ds.Table["ITEMS"].Rows)
        {
            int itemId = Comvert.ToInt32(itemDR["ITEMS"]);
            sb.Append(itemId.ToString() + strDelimiter);
            sb.Append(itemDR["ITEMS"].ToString() + strDelimiter);
            sb.Append(itemDR["QUANT"].ToString() + strDelimiter);
            sb.Append(itemDR["SIZE"].ToString() + strDelimiter);
            sb.Append(itemDR["COLOR"].ToString() + strDelimiter);
            sb.Append(itemDR["PRICE\n"].ToString() + strDelimiter);
            sb.Append("\r\n");
        }



        {
            string strFileName = "thefile.xls";


            StreamWriter file = new StreamWriter(@"C:\Users\debom_000\Desktop\Data\" + strFileName);
            file.WriteLine(sb.ToString());
            File.Close();
            connection.Close(); // Close connection

            //Have program pause to keep from closing console window



        }
    }
}

}

您好如果您使用的是MySQL,您可以使用内置的SELECT INTO OUTFILE生成excel文件

SELECT * INTO OUTFILE "C:\Users\debom_000\Desktop\Data\export_table_data_excel.xls" 
FIELDS TERMINATED BY '\t' 
LINES TERMINATED BY '\n' 
FROM database_name.table_name;

是否已将System.Reflection和System.IO添加到名称空间?我已通过“使用System.IO”而不是System.Reflection添加了System.IO。如何实现代码?请考虑使用EPPLUS。这是迄今为止创建良好工作的Excel文件最简单的方法。@OldZero您也可以使用Interop.Excel-在这里通读答案:@Jeff Orris-这看起来非常接近我要做的。唯一的问题是,我知道在程序编译后(如果我能让它工作的话),需要为MS Excel生成一个CSV文件。我需要通过cmd提示符风格的程序来完成这项工作。