将每个数据导出为ex​​cel表格或任何格式

时间:2012-02-20 08:10:35

标签: c# asp.net export-to-excel

我必须将每个数据导出为ex​​cel表格或蚂蚁格式,如pdf,word等。我该怎么办(将数据写入任何格式)...我有html中的dispalye数据..i必须以字或任何格式导出。

public void Function(string fname) {

strhtmlcontent.Append("<div id='id1'><table align='Center' style='background-color:Silver' BORDER-COLLAPSE:collapse cellSpacing=0 rules=all border=1 width='100%'><th width=8%>FirstName</th><th width=15%>Product Name</th><th width=15%>Client Name</th><th width=10%>Amount</th><th width=15%>Activity Date</th>");

SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

scon.Open();
if (fname == "All")
{
    scmd = new SqlCommand("SELECT usermaster.firstname, Product_Master.product_name, Product_Master.client_name, Product_Master.amount, Product_Master.activity_date FROM usermaster INNER JOIN Product_Master ON usermaster.product_id = Product_Master.product_id", scon);
}
else
{

    scmd = new SqlCommand("SELECT usermaster.firstname, Product_Master.product_name, Product_Master.client_name, Product_Master.amount, Product_Master.activity_date FROM usermaster INNER JOIN Product_Master ON usermaster.product_id = Product_Master.product_id where firstname='"+fname+"'", scon);

}
 dr = scmd.ExecuteReader();       




string firstname = "", product_name = "", activity_date = "";

string client_name = "", amount = "";

while (dr.Read())
{
    firstname = dr["firstname"].ToString();
    product_name = dr["product_name"].ToString();
    client_name = dr["client_name"].ToString();
    amount = dr["amount"].ToString();
    activity_date = dr["activity_date"].ToString();


    strhtmlcontent.Append("<tr><td align='center'>" + firstname + "&nbsp;</td><td align='center'>" + product_name + "&nbsp;</td><td align='center'>" + client_name + "&nbsp;</td><td align='center'>" + amount + "&nbsp;</td><td align='center'>" + activity_date + "&nbsp;</td></tr>");


}

dr.Close();
strhtmlcontent.Append("</table></div>");
HttpContext.Current.Response.Write(strhtmlcontent);       
HttpContext.Current.Response.Flush();
//HttpContext.Current.Response.End();

}

2 个答案:

答案 0 :(得分:1)

使用ADO.NET

连接字符串应该是这样的: -

string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Book1.xls;Extended Properties=""Excel 8.0;HDR=YES;""";

实施例

DbProviderFactory factory =   DbProviderFactories.GetFactory("System.Data.OleDb");

using (DbConnection connection = factory.CreateConnection())
{
    connection.ConnectionString = connectionString;

    using (DbCommand command = connection.CreateCommand())
    {
        command.CommandText = "INSERT INTO [Cities$] (ID, City, State) VALUES(4,\"Tampa\",\"Florida\")";

        connection.Open();

        command.ExecuteNonQuery();
    }
}

参考 Reading and Writing Excel Spreadsheets Using ADO.NET C# DbProviderFactory

答案 1 :(得分:1)

你可以使用一些商业图书馆吗?您可以尝试使用Syncfusion的XlsIO,PdfIO,DocIO。

http://www.syncfusion.com/products/reporting-edition