0

我是 Silverlight 的新手。

我将 VS-2008 与 Silverlight 3、SQL Server 2005 一起使用。

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

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

有人可以指导我怎么做吗?

提前谢谢,

4

1 回答 1

0

最简单的方法是使用 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

于 2012-10-07T07:51:17.347 回答