2012-10-07 57 views

回答

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

+0

Hidde嗨, 非常感謝您的回覆;但是,我不允許在服務器上安裝新軟件(NPOI)。服務器位於法國,我在印度。因此,你能否給我建議一些不需要安裝其他軟件的方法? –

+0

你可以看看這個:http://www.rshelby.com/post/exporting-data-from-silverilght-datagrid-to-excel.aspx – 2012-10-08 14:49:54

+0

嗨Hidde。 在您給出的鏈接中,我們可以將數據從DataGrid導出到Excel,而不是從數據庫導出到Excel。正如我的文章解釋了我的要求,我想要一些功能將數據從數據庫導出到Excel。 –

相關問題