如何在 Silverlight 3 中将 SQL Server 数据库数据导出到 Excel 中



我是Silverlight的新手。

我正在使用VS-2008和Silverlight 3,SQL Server 2005。

我的要求是:我必须从数据库中检索数据并导出到Excel。

我已经用谷歌搜索过,但我没有得到正确的链接或材料来满足我的要求。

任何人都可以指导我怎么做吗?

提前感谢,

最简单的方法是使用NPOI(npoi.codeplex.com)。

基本上,您可以在 xaml 中定义以下事件:

private void Button_Click(object sender, RoutedEventArgs e)
{
    WebClient client = new WebClient();
    client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
    client.DownloadStringAsync(new Uri("DownloadFile.aspx", UriKind.Absolute));
}

并在服务器项目页面 DownloadFile.aspx 中执行以下操作之后:

using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
public partial class DownloadFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
    string filename = "test.xls";
    Response.ContentType = "application/vnd.ms-excel";
    Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename));
    Response.Clear();
    InitializeWorkbook();
    GenerateData();
    Response.BinaryWrite(WriteToStream().GetBuffer());
    Response.End();
}
HSSFWorkbook hssfworkbook;
MemoryStream WriteToStream()
{
    //Write the stream data of workbook to the root directory
    MemoryStream file = new MemoryStream();
    hssfworkbook.Write(file);
    return file;
}
void GenerateData()
{
    Sheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
    sheet1.CreateRow(0).CreateCell(0).SetCellValue("This is a Sample");
    int x = 1;
    for (int i = 1; i <= 15; i++)
    {
        Row row = sheet1.CreateRow(i);
        for (int j = 0; j < 15; j++)
        {
            // add you data from the db
            row.CreateCell(j).SetCellValue(x++);
        }
    }
}
void InitializeWorkbook()
{
    hssfworkbook = new HSSFWorkbook();
    ////create a entry of DocumentSummaryInformation
    DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
    dsi.Company = "NPOI Team";
    hssfworkbook.DocumentSummaryInformation = dsi;
    ////create a entry of SummaryInformation
    SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
    si.Subject = "NPOI SDK Example";
    hssfworkbook.SummaryInformation = si;
    }
}

另请查看 NPOI 版本中的示例... 我希望它有所帮助!

来源:http://go4answers.webhost4life.com/Question/easiest-npoi-codeplex-basically-define-817046.aspx

最新更新