【发布时间】:2015-03-16 00:19:43
【问题描述】:
我和一位同事正在做一项任务,需要将 SQL Server 的简单数据传输到 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
}
}
}
}
【问题讨论】:
-
您是否将 System.Reflection 和 System.IO 添加到您的命名空间?
-
我通过“使用 System.IO”而不是 System.Reflection 添加了 System.IO。我将如何在代码中实现它?
-
考虑使用 EPPlus link。这是迄今为止创建良好工作 Excel 文件的最简单方法。
-
@OldZero 您也可以使用 Interop.Excel - 在此处阅读答案:social.msdn.microsoft.com/Forums/vstudio/en-US/…
-
@Jeff Orris - 这看起来非常接近我想要做的事情。唯一的事情是我知道程序编译后(如果我可以让它工作)需要生成一个 CSV 文件用于 MS Excel。
标签: c# sql excel export-to-excel