在asp.net中的Excel下载库?

我们有没有免费的第三方库,我们可以在asp.net中使用下载Excel工作表? 请给我一些。

我使用和NPOI一样: http : //npoi.codeplex.com/

您可能不需要第三方工具来从数据库检索数据并将其导出到Excel文件。 此代码将使用HTML从DataView生成单个工作表Excel文件,使其看起来非常漂亮。

您需要将数据检索到包含一个DataTableDataSet dstExcel中,该DataSet dstExcel包含您在Excel电子表格中所需的数据。

GenerateExcelFile(dstExcel, fileName );

这里是代码隐藏:

 private void GenerateExcelFile(DataSet dst, string fileName) { // Clear any current output from the buffer. Response.Clear(); // "Content-Disposition" & "attachment;filename=" are used to specify the default filename for the downloaded file. Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); Response.ContentType = "application/vnd.ms-excel"; DataView dvw = dst.Tables[0].DefaultView; if ((dvw != null) && (dvw.Table.Rows.Count > 0)) { // We're exporting an HTML table. Table tbl = ConvertDataViewToHTMLTable(dvw); StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); tbl.RenderControl(hw); Response.Write(sw.ToString()); Response.End(); } } private Table ConvertDataViewToHTMLTable(DataView dvw) { Table tbl = new Table(); TableRow trw; TableCell tcl; Label lbl; DataColumn col; tbl.BorderColor = Color.Black; tbl.BorderWidth = Unit.Pixel(1); tbl.BorderStyle = BorderStyle.Solid; // Begin with a table row containing column names. trw = new TableRow(); for (int i = 0; i < dvw.Table.Columns.Count; i++) { col = dvw.Table.Columns[i]; // Add column name. lbl = new Label(); lbl.Text = col.ColumnName; tcl = new TableCell(); tcl.Controls.Add(lbl); tcl.BackColor = Color.MediumSeaGreen; tcl.ForeColor = Color.PaleGoldenrod; tcl.HorizontalAlign = HorizontalAlign.Center; tcl.Style["Font"] = "Tahoma"; tcl.Style["Font-Weight"] = "Bold"; trw.Controls.Add(tcl); } tbl.Controls.Add(trw); // Add records containg row data. DataRow row; for (int i = 0; i < dvw.Table.Rows.Count; i++) { row = dvw.Table.Rows[i]; trw = new TableRow(); for (int j = 0; j < dvw.Table.Columns.Count; j++) { col = dvw.Table.Columns[j]; lbl = new Label(); lbl.Text = row[col.ColumnName].ToString(); tcl = new TableCell(); tcl.Controls.Add(lbl); tcl.BorderColor = Color.LightGray; tcl.BorderWidth = Unit.Pixel(1); tcl.Style["Font"] = "Tahoma"; trw.Controls.Add(tcl); } tbl.Controls.Add(trw); } return tbl; } 

EPPlus非常适合在服务器上创buildExcel文件。

Microsoft提供了用于编程创buildexcel文档的Interop 。 您也可以select购买Telerik控件,它提供了一个类似gridview的控件,并具有保存到Excel格式的保存function。 我没有这么做,所以细节不是很清楚,但你可以联系他们的支持获取更多的信息。

您可以使用报告定义语言。 我的方法有点破解,但它做的工作,没有第三方程序集的需要。 将报表查看器控件( http://msdn.microsoft.com/en-us/library/ms251670(VS.80).aspx )拖动到您的devise器上。 转到标记,然后将报告查看器包裹在div元素中,并将style.display属性设置为none。

然后,您可以编程生成Excel文件(在我的例子中,我输出了一个PDF,并需要执行模拟,因为outfile被写入到Doc服务器):

  Dim aa As AliasAccount = New AliasAccount("ASP.NET", "Uiop_4567") ' Begin Impersonation aa.BeginImpersonation() iRetVal = ExportCoverLetter() If iRetVal = 0 Then Dim bytes() As Byte = report.Render( _ "PDF", Nothing, sMimeType, sEncoding, sFileNameExtension, _ sStreamids, warnings) Using fs As FileStream = New FileStream(sApplicationPath, FileMode.Create) fs.Write(bytes, 0, bytes.Length) End Using ' End of Impersonation aa.EndImpersonation() ' success Return 0 Else Return -1 End If 

一旦生成文件,你需要以某种方式输出。 我使用了AjaxControlKit.Modalpopup式扩展器。 我将TargetControlID属性绑定到一个隐藏的button,并将PopUpControlID设置为一个ASP面板,显示一个链接说PDF:

  <asp:ImageButton ID="btnSearch2" runat="server" ImageUrl="~/images/buttons/btnSearch.jpg" AlternateText="Search" style="display:none;"/> <asp:Panel ID="panSendPDFToClient" runat="server" Height="100px" Width="300px" BorderStyle="Solid" CssClass="ModalPopup" style="display:none;background-color:White"> <table width="100%"> <tr><td align = "center" style="width: 497px"><asp:Label style="width:inherit; text-align:center; color:Black; font-weight:bold;" ID = "hlbl" Text = "Please click View PDF to download file." runat= "server"></asp:Label></td></tr> <tr> <td class="formtext" style="height: 23px; width: 497px;" align="center" valign="middle"> <a id="lkSendPdfToClient" runat="server" href="sendpdftoclient.aspx" target="_blank" style ="font-size:12pt;" onclick="return lkSendPdfToClient_onclick()" >View PDF</a> <br /> </td> </tr> <tr><td align = "center" style="width: 497px"><asp:Button ID="btnCancel" runat="server" Text="Cancel" /></td></tr> </table> <br/> </asp:Panel> 

当用户点击查看PDF时,会popup一个新窗口。 文档path可以通过查询string或会话传入。 在新窗口中获取文档path,清除HTTPContext缓冲区,更改内容types并附加文件。

 Private Function SendPDFToClient(ByVal sPDFfilePath As String, ByVal sFileName As String, ByRef oReturnException As System.Exception) As Integer ' variables Dim oMethodBase As MethodBase = MethodBase.GetCurrentMethod() Dim METHOD_NAME As String = oMethodBase.DeclaringType.ToString() & "." & oMethodBase.Name.ToString() Try Dim aa As AliasAccount = New AliasAccount("ASP.NET", "Uiop_4567") ' Begin Impersonation aa.BeginImpersonation() Dim fs As System.IO.FileStream Dim br As System.IO.BinaryReader fs = New System.IO.FileStream(sPDFfilePath, System.IO.FileMode.Open) br = New System.IO.BinaryReader(fs) Dim oByteArray As Byte() = br.ReadBytes(fs.Length - 1) br.Close() ' End of Impersonation aa.EndImpersonation() lblHiddenFileExist.Text = "File Exist=" & System.IO.File.Exists(sPDFfilePath) & ControlChars.NewLine _ & " ByteArray Length=" & oByteArray.Length().ToString() HttpContext.Current.Response.Buffer = True HttpContext.Current.Response.Clear() HttpContext.Current.Response.ClearContent() HttpContext.Current.Response.ClearHeaders() HttpContext.Current.Response.ContentType = "application/pdf" HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" & sFileName) HttpContext.Current.Response.BinaryWrite(oByteArray) HttpContext.Current.Response.Flush() HttpContext.Current.Response.Close() ' success Return 0 Catch exThreadAbort As Threading.ThreadAbortException ' do nothing Catch ex As Exception ' failure ex.Data.Add("METHOD_NAME", METHOD_NAME) oReturnException = ex Return -1 End Try End Function 

最终的结果是一个窗口提示用户是否要保存或打开文档。 希望这可以帮助。