我们是否有可以在 ASP.NET 中使用的免费第 3 方库来下载 Excel 表格?请给我一些。
最佳答案
您可能不需要第三方工具只是从数据库检索数据并将其导出到 Excel 文件。 此代码将使用 HTML 从 DataView 生成单个工作表 Excel 文件,使其看起来更漂亮。
您需要将数据检索到 DataSet dstExcel
中,其中包含一个 DataTable
,其中包含您想要在 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;
}
关于c# - asp.net 中的 Excel 下载库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3088217/