‘Calls stored proc in SQL Server 2000 and puts data in Excel and ‘formats it
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cnn As ADODB.Connection
cnn = New ADODB.Connection
cnn.Open("Provider=SQLOLEDB;data source=xxxxxxx;" & _
"database=xxxxxxxx;Trusted_Connection=yes;")
Dim cmd As New ADODB.Command
cmd.ActiveConnection = cnn
cmd.CommandText = "[sp_TomTepley]"
cmd.CommandType = ADODB.CommandTypeEnum.adCmdStoredProc
cmd.CommandTimeout = 0
cmd.Parameters.Refresh()
Dim rst1 As ADODB.Recordset
rst1 = New ADODB.Recordset
rst1.Open(cmd)
Dim oXL As New Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
'oXL = CreateObject("excel.application")
oXL.Visible = True
oWB = oXL.Workbooks.Add
oSheet = oWB.ActiveSheet
Dim Column As Integer
Column = 1
Dim fld As ADODB.Field
For Each fld In rst1.Fields
oXL.Workbooks(1).Worksheets(1).Cells(1, Column).Value = fld.Name
oXL.Workbooks(1).Worksheets(1).cells(1, Column).Interior.ColorIndex = 15
Column = Column + 1
Next fld
oXL.Workbooks(1).Worksheets(1).name = "Tom Tepley Report"
oSheet.Cells(2, 1).copyfromrecordset(rst1)
oXL.Workbooks(1).Worksheets(1).Cells.EntireColumn.AutoFit()
oXL.Visible = True
oXL.UserControl = True
rst1 = Nothing
cnn.Close()
Beep()
End Sub
Here's a report that pulls from a stored procedure. The results are exported to Excel. It uses ADO instead of ADO.NET and the reason why is this line
oSheet.Cells(2, 1).copyfromrecordset(rst1)
It does most of the work and isn't available in ado.net.
‘Calls stored proc in SQL Server 2000 and puts data in Excel and ‘formats it
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cnn As ADODB.Connection
cnn = New ADODB.Connection
cnn.Open("Provider=SQLOLEDB;data source=xxxxxxx;" & _
"database=xxxxxxxx;Trusted_Connection=yes;")
Dim cmd As New ADODB.Command
cmd.ActiveConnection = cnn
cmd.CommandText = "[sp_TomTepley]"
cmd.CommandType = ADODB.CommandTypeEnum.adCmdStoredProc
cmd.CommandTimeout = 0
cmd.Parameters.Refresh()
Dim rst1 As ADODB.Recordset
rst1 = New ADODB.Recordset
rst1.Open(cmd)
Dim oXL As New Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
'oXL = CreateObject("excel.application")
oXL.Visible = True
oWB = oXL.Workbooks.Add
oSheet = oWB.ActiveSheet
Dim Column As Integer
Column = 1
Dim fld As ADODB.Field
For Each fld In rst1.Fields
oXL.Workbooks(1).Worksheets(1).Cells(1, Column).Value = fld.Name
oXL.Workbooks(1).Worksheets(1).cells(1, Column).Interior.ColorIndex = 15
Column = Column + 1
Next fld
oXL.Workbooks(1).Worksheets(1).name = "Tom Tepley Report"
oSheet.Cells(2, 1).copyfromrecordset(rst1)
oXL.Workbooks(1).Worksheets(1).Cells.EntireColumn.AutoFit()
oXL.Visible = True
oXL.UserControl = True
rst1 = Nothing
cnn.Close()
Beep()
End Sub
I would just create a CSV file based on the data, because I see that as the cleanest, and Excel has good support for it. But if you require a more flexible format, I'm sure there's some 3rd party tools for generating real excel files.
One of the problems I've ran across using one of the solutions suggested above which are similar to this answer is that if you push the content out as an attachment (what I've found to be the cleanest solution for non-ms browsers), then open it in Excel 2000-2003, its type is an "Excel Web Page" and not a native Excel document.
Then you have to explain to users how to use "Save as type" from within Excel to convert it to an Excel document. This is a pain if users need to edit this document and then re-upload it to your site.
My recommendation is to use CSV. It's simple and if users do open it from within Excel, Excel at least prompts them to save it in its native format.
我不确定我是否真的会再推荐这种方法,除非是在相当小众的场景中,但它在经典 ASP 的鼎盛时期相当常见。
Assuming this is for an intranet, where you can set permissions and mandate IE, you can generate the workbook client side with JScript/VBScript driving Excel. This gives you native Excel formatting, without the hassle of trying to automate Excel on the server.
I'm not sure I'd really recommend this approach anymore except in fairly niche scenarios, but it was fairly common during the classic ASP heydays.
您可以将数据输出为 html 表格单元格,在其上粘贴 .xls 或 .xlsx 扩展名,Excel 将打开它,就像打开本机文档一样。 您甚至可以通过这种方式进行一些有限的格式化和公式计算,因此它比 CSV 强大得多。 此外,从像 ASP.Net 这样的 Web 平台输出 html 表格应该非常容易;)
You can output the data as html table cells, stick a .xls or .xlsx extension on it, and Excel will open it as if it were a native document. You can even do some limited formatting and formula calculations this way, so it's much more powerful than CSV. Also, outputting an html table ought to be pretty easy to do from a web platform like ASP.Net ;)
If you need multiple worksheets or named worksheets within your Excel Workbook, you can do something similar via an XML schema called SpreadSheetML. This is not the new format that shipped with Office 2007, but something completely different that works as far back as Excel 2000. The easiest way to explain how it works is with an example:
public static void DataTabletoXLS(DataTable DT, string fileName)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "utf-16";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xls", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
string tab = "";
foreach (DataColumn dc in DT.Columns)
{
HttpContext.Current.Response.Write(tab + dc.ColumnName.Replace("\n", "").Replace("\t", ""));
tab = "\t";
}
HttpContext.Current.Response.Write("\n");
int i;
foreach (DataRow dr in DT.Rows)
{
tab = "";
for (i = 0; i < DT.Columns.Count; i++)
{
HttpContext.Current.Response.Write(tab + dr[i].ToString().Replace("\n", "").Replace("\t", ""));
tab = "\t";
}
HttpContext.Current.Response.Write("\n");
}
HttpContext.Current.Response.End();
}
来自Gridview:
public static void GridviewtoXLS(GridView gv, string fileName)
{
int DirtyBit = 0;
int PageSize = 0;
if (gv.AllowPaging == true)
{
DirtyBit = 1;
PageSize = gv.PageSize;
gv.AllowPaging = false;
gv.DataBind();
}
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "utf-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}.xls", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a table to contain the grid
Table table = new Table();
// include the gridline settings
table.GridLines = gv.GridLines;
// add the header row to the table
if (gv.HeaderRow != null)
{
Utilities.Export.PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
Utilities.Export.PrepareControlForExport(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
Utilities.Export.PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
// render the table into the htmlwriter
table.RenderControl(htw);
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString().Replace("£", ""));
HttpContext.Current.Response.End();
}
if (DirtyBit == 1)
{
gv.PageSize = PageSize;
gv.AllowPaging = true;
gv.DataBind();
}
}
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
if (current.HasControls())
{
Utilities.Export.PrepareControlForExport(current);
}
}
}
If coming from a DataTable:
public static void DataTabletoXLS(DataTable DT, string fileName)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "utf-16";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xls", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
string tab = "";
foreach (DataColumn dc in DT.Columns)
{
HttpContext.Current.Response.Write(tab + dc.ColumnName.Replace("\n", "").Replace("\t", ""));
tab = "\t";
}
HttpContext.Current.Response.Write("\n");
int i;
foreach (DataRow dr in DT.Rows)
{
tab = "";
for (i = 0; i < DT.Columns.Count; i++)
{
HttpContext.Current.Response.Write(tab + dr[i].ToString().Replace("\n", "").Replace("\t", ""));
tab = "\t";
}
HttpContext.Current.Response.Write("\n");
}
HttpContext.Current.Response.End();
}
From a Gridview:
public static void GridviewtoXLS(GridView gv, string fileName)
{
int DirtyBit = 0;
int PageSize = 0;
if (gv.AllowPaging == true)
{
DirtyBit = 1;
PageSize = gv.PageSize;
gv.AllowPaging = false;
gv.DataBind();
}
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "utf-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}.xls", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a table to contain the grid
Table table = new Table();
// include the gridline settings
table.GridLines = gv.GridLines;
// add the header row to the table
if (gv.HeaderRow != null)
{
Utilities.Export.PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
Utilities.Export.PrepareControlForExport(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
Utilities.Export.PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
// render the table into the htmlwriter
table.RenderControl(htw);
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString().Replace("£", ""));
HttpContext.Current.Response.End();
}
if (DirtyBit == 1)
{
gv.PageSize = PageSize;
gv.AllowPaging = true;
gv.DataBind();
}
}
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
if (current.HasControls())
{
Utilities.Export.PrepareControlForExport(current);
}
}
}
根据给出的答案以及与同事的协商,最好的解决方案似乎是生成 XML 文件或 HTML 表格并将其作为附件推送下来。 我的同事建议的一项更改是数据(即 HTML 表)可以直接写入 Response 对象,从而消除了写出文件的需要,因为权限问题、I/O 问题可能会很麻烦。争用,并确保进行计划的清除。
这是代码片段...我还没有检查过这一点,也没有提供所有调用的代码,但我认为它很好地代表了这个想法。
Dim uiTable As HtmlTable = GetUiTable(groupedSumData)
Response.Clear()
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader("Content-Disposition", String.Format("inline; filename=OSSummery{0:ddmmssf}.xls", DateTime.Now))
Dim writer As New System.IO.StringWriter()
Dim htmlWriter As New HtmlTextWriter(writer)
uiTable.RenderControl(htmlWriter)
Response.Write(writer.ToString)
Response.End()
Based on the answers given, and consultation with coworkers, it appears that the best solution is to generate either an XML file or HTML tables and push it down as an attachment. The one change recommended by my co-workers is that the data (i.e. the HTML tables) can be written directly to the Response object, thus eliminating the need to write out a file, which can be troublesome due to permissions problems, I/O contention, and ensuring that scheduled purging occurs.
Here's a snippet of the code... I haven't checked this yet, and I haven't supplied all the called code, but I think it represents the idea well.
Dim uiTable As HtmlTable = GetUiTable(groupedSumData)
Response.Clear()
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader("Content-Disposition", String.Format("inline; filename=OSSummery{0:ddmmssf}.xls", DateTime.Now))
Dim writer As New System.IO.StringWriter()
Dim htmlWriter As New HtmlTextWriter(writer)
uiTable.RenderControl(htmlWriter)
Response.Write(writer.ToString)
Response.End()
如果您想避免临时文件,则可以写入 如果省略了内容长度标头,则可以直接将 html 写回内存中流并写回字节,而不是使用 WriteFile
,但这可能无法在所有浏览器中始终正常工作
since Excel understands HTML you can just write the data out as an HTML table to a temp file with an .xls extension, get the FileInfo for the file, and blow it back using
我个人更喜欢XML方法。 我将从数据集中返回数据库中的数据,将其保存到 XMl,然后创建一个 xslt 文件,其中包含将格式化正确文档的转换规则,并且简单的 XML 转换将完成该工作。 最好的部分是您可以设置单元格格式、条件格式、设置页眉和页脚,甚至设置打印范围。
I personally prefer the XML method. I'll return the data from the database in a Dataset, save it to XMl, then I create an xslt file that contains a transformation rule that will format a proper document, and a simple XML transform will finish the job up. The best part of about this you can format cells, do conditional formatting, setup headers and footers, and even set print ranges.
I've done this a couple of times and each time the easiest way was to simply return a CSV (Comma Separated Value) file. Excel imports it perfectly, and it's relatively fast to do.
Response.ContentType = "application/vnd.ms-excel"
Response.Charset = ""
Response.AddHeader("content-disposition", "fileattachment;filename=YOURFILENAME.xls")
Me.EnableViewState = False
Dim sw As System.IO.StringWriter = New System.IO.StringWriter
Dim hw As HtmlTextWriter = New HtmlTextWriter(sw)
ClearControls(grid)
grid.RenderControl(hw)
Response.Write(sw.ToString())
Response.End()
这种方法的唯一问题是,我们的许多网格中都有按钮或链接,因此您也需要这个:
'needed to export grid to excel to remove link button control and represent as text
Private Sub ClearControls(ByVal control As Control)
Dim i As Integer
For i = control.Controls.Count - 1 To 0 Step -1
ClearControls(control.Controls(i))
Next i
If TypeOf control Is System.Web.UI.WebControls.Image Then
control.Parent.Controls.Remove(control)
End If
If (Not TypeOf control Is TableCell) Then
If Not (control.GetType().GetProperty("SelectedItem") Is Nothing) Then
Dim literal As New LiteralControl
control.Parent.Controls.Add(literal)
Try
literal.Text = CStr(control.GetType().GetProperty("SelectedItem").GetValue(control, Nothing))
Catch
End Try
control.Parent.Controls.Remove(control)
Else
If Not (control.GetType().GetProperty("Text") Is Nothing) Then
Dim literal As New LiteralControl
control.Parent.Controls.Add(literal)
literal.Text = CStr(control.GetType().GetProperty("Text").GetValue(control, Nothing))
control.Parent.Controls.Remove(control)
End If
End If
End If
Return
End Sub
我发现在某个地方,它运行良好。
we export data from a datagrid to excel all the time. Converting it to HTML then writing to an excel file
Response.ContentType = "application/vnd.ms-excel"
Response.Charset = ""
Response.AddHeader("content-disposition", "fileattachment;filename=YOURFILENAME.xls")
Me.EnableViewState = False
Dim sw As System.IO.StringWriter = New System.IO.StringWriter
Dim hw As HtmlTextWriter = New HtmlTextWriter(sw)
ClearControls(grid)
grid.RenderControl(hw)
Response.Write(sw.ToString())
Response.End()
The only gotcha with this method was that a lot of our grids had buttons or links in them so you need this too:
'needed to export grid to excel to remove link button control and represent as text
Private Sub ClearControls(ByVal control As Control)
Dim i As Integer
For i = control.Controls.Count - 1 To 0 Step -1
ClearControls(control.Controls(i))
Next i
If TypeOf control Is System.Web.UI.WebControls.Image Then
control.Parent.Controls.Remove(control)
End If
If (Not TypeOf control Is TableCell) Then
If Not (control.GetType().GetProperty("SelectedItem") Is Nothing) Then
Dim literal As New LiteralControl
control.Parent.Controls.Add(literal)
Try
literal.Text = CStr(control.GetType().GetProperty("SelectedItem").GetValue(control, Nothing))
Catch
End Try
control.Parent.Controls.Remove(control)
Else
If Not (control.GetType().GetProperty("Text") Is Nothing) Then
Dim literal As New LiteralControl
control.Parent.Controls.Add(literal)
literal.Text = CStr(control.GetType().GetProperty("Text").GetValue(control, Nothing))
control.Parent.Controls.Remove(control)
End If
End If
End If
Return
End Sub
如果您用数据填充 GridView,则可以使用此函数获取 HTML 格式的数据,但会向浏览器指示它是一个 Excel 文件。
Public Sub ExportToExcel(ByVal fileName As String, ByVal gv As GridView)
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName))
HttpContext.Current.Response.ContentType = "application/ms-excel"
Dim sw As StringWriter = New StringWriter
Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
Dim table As Table = New Table
table.GridLines = gv.GridLines
If (Not (gv.HeaderRow) Is Nothing) Then
PrepareControlForExport(gv.HeaderRow)
table.Rows.Add(gv.HeaderRow)
End If
For Each row As GridViewRow In gv.Rows
PrepareControlForExport(row)
table.Rows.Add(row)
Next
If (Not (gv.FooterRow) Is Nothing) Then
PrepareControlForExport(gv.FooterRow)
table.Rows.Add(gv.FooterRow)
End If
table.RenderControl(htw)
HttpContext.Current.Response.Write(sw.ToString)
HttpContext.Current.Response.End()
End Sub
Private Sub PrepareControlForExport(ByVal control As Control)
Dim i As Integer = 0
Do While (i < control.Controls.Count)
Dim current As Control = control.Controls(i)
If (TypeOf current Is LinkButton) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, LinkButton).Text))
ElseIf (TypeOf current Is ImageButton) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, ImageButton).AlternateText))
ElseIf (TypeOf current Is HyperLink) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, HyperLink).Text))
ElseIf (TypeOf current Is DropDownList) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, DropDownList).SelectedItem.Text))
ElseIf (TypeOf current Is CheckBox) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, CheckBox).Checked))
End If
If current.HasControls Then
PrepareControlForExport(current)
End If
i = i + 1
Loop
End Sub
If you fill a GridView with data you can use this function to get the HTML formatted data, but indicating the browser it's an excel file.
Public Sub ExportToExcel(ByVal fileName As String, ByVal gv As GridView)
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName))
HttpContext.Current.Response.ContentType = "application/ms-excel"
Dim sw As StringWriter = New StringWriter
Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
Dim table As Table = New Table
table.GridLines = gv.GridLines
If (Not (gv.HeaderRow) Is Nothing) Then
PrepareControlForExport(gv.HeaderRow)
table.Rows.Add(gv.HeaderRow)
End If
For Each row As GridViewRow In gv.Rows
PrepareControlForExport(row)
table.Rows.Add(row)
Next
If (Not (gv.FooterRow) Is Nothing) Then
PrepareControlForExport(gv.FooterRow)
table.Rows.Add(gv.FooterRow)
End If
table.RenderControl(htw)
HttpContext.Current.Response.Write(sw.ToString)
HttpContext.Current.Response.End()
End Sub
Private Sub PrepareControlForExport(ByVal control As Control)
Dim i As Integer = 0
Do While (i < control.Controls.Count)
Dim current As Control = control.Controls(i)
If (TypeOf current Is LinkButton) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, LinkButton).Text))
ElseIf (TypeOf current Is ImageButton) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, ImageButton).AlternateText))
ElseIf (TypeOf current Is HyperLink) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, HyperLink).Text))
ElseIf (TypeOf current Is DropDownList) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, DropDownList).SelectedItem.Text))
ElseIf (TypeOf current Is CheckBox) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, CheckBox).Checked))
End If
If current.HasControls Then
PrepareControlForExport(current)
End If
i = i + 1
Loop
End Sub
CSV is easiest way. Most of the time it is linked to Excel. Otherwise you have to use the automation APIs or XML format. The APIs and XML are not that hard to use.
I either go the CSV route (as described above), or more often these days, I use Infragistics NetAdvantage to generate the file. (The very vast majority of the time where Infragistics is in play, we're just exporting an existing UltraWebGrid, which is essentially a one-LOC solution unless extra formatting tweaks are needed. We could manually generate an Excel/BIFF file as well, but there's rarely a need to.)
伙计,在.net中我想你可以有一个组件可以做到这一点,但是在经典的asp中我已经完成了创建一个html表并将页面的mimetipe更改为vnd/msexcel。 我想如果你使用 gridview 并更改 mime 类型也许它应该可以工作,因为 gridview 是一个 html 表。
man, in .net i guess you could have a component that could do that, but in classic asp I have already done it creating an html table and changing the mime tipe of the page to vnd/msexcel. I guess that if you use a gridview and change the mime type maybe it should work, because the gridview is an html table.
避免“看起来这些数字存储为文本”绿色三角形的唯一万无一失的方法是使用 Open XML 格式。 值得使用它,只是为了避免不可避免的绿色三角形。
The only bulletproof way of avoiding the "It looks like these numbers are stored as text" green triangles is to use the Open XML format. It is worth using it, just to avoid the inevitable green triangles.
我见过的 Excel 报告的最佳方法是使用 XML 扩展以 XML 格式写出数据,并将其以正确的内容类型流式传输到客户端。 (应用程序/xls)
这适用于任何需要基本格式的报告,并允许您使用文本比较工具与现有电子表格进行比较。
The best method i've seen for excel reports is to write out the data in XML with a XML extension and stream it to clients with the correct content type. (application/xls)
This works for any report which requires basic formating, and allows you to compare against existing spreadsheets by using text comparison tools.
public void ExportFileFromSPData(string filename, DataTable dt)
{
HttpResponse response = HttpContext.Current.Response;
//clean up the response.object
response.Clear();
response.Buffer = true;
response.Charset = "";
// set the response mime type for html so you can see what are you printing
//response.ContentType = "text/html";
//response.AddHeader("Content-Disposition", "attachment;filename=test.html");
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
response.ContentEncoding = System.Text.Encoding.UTF8;
response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
//style to format numbers to string
string style = @"<style> .text { mso-number-format:\@; } </style>";
response.Write(style);
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
GridView dg = new GridView();
dg.DataSource = dt;
dg.DataBind();
foreach (GridViewRow datarow in dg.Rows)
{
//format specific cell to be text
//to avoid 1.232323+E29 to get 1232312312312312124124
datarow.Cells[0].Attributes.Add("class", "text");
}
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
just created a function to export from a web form C# to excel hope it helps others
public void ExportFileFromSPData(string filename, DataTable dt)
{
HttpResponse response = HttpContext.Current.Response;
//clean up the response.object
response.Clear();
response.Buffer = true;
response.Charset = "";
// set the response mime type for html so you can see what are you printing
//response.ContentType = "text/html";
//response.AddHeader("Content-Disposition", "attachment;filename=test.html");
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
response.ContentEncoding = System.Text.Encoding.UTF8;
response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
//style to format numbers to string
string style = @"<style> .text { mso-number-format:\@; } </style>";
response.Write(style);
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
GridView dg = new GridView();
dg.DataSource = dt;
dg.DataBind();
foreach (GridViewRow datarow in dg.Rows)
{
//format specific cell to be text
//to avoid 1.232323+E29 to get 1232312312312312124124
datarow.Cells[0].Attributes.Add("class", "text");
}
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
密切关注资源使用情况。 通过 OLE 自动化接口生成电子表格(PIA 只是其上的垫片)是一个相当重量级的过程。 如果您需要将其扩展到高数据量,您可能需要对您的架构进行一些巧妙的处理。
如果您不介意文件格式有点基本,那么某些“使用 mime 类型诱骗 excel 打开 HTML 表”方法就可以使用。 这些方法还将 CPU 的繁重工作转移到客户端上。 如果您想要对电子表格的格式进行精细控制,您可能必须使用 Excel 本身来生成如上所述的文件。
If you have to use Excel instead of a CSV file you will need to use OLE automation on an Excel instance one the server. The easiest way to do this is to have a template file and programatically fill it in with the data. You save it to another file.
Tips:
Don't do it interactively. Have the user kick off the process and then post a page with the link to the file. This mitigates potential performance issues while the spreadsheet is generated.
Use the template as I described before. It makes it easier to modify it.
Make sure that Excel is set to not pop up dialogs. On a web server this will hang the whole excel instance.
Keep the Excel instance on a separate server, preferably behind a firewall, so it is not exposed as a potential security hole.
Keep an eye on resource usage. Generating a spreadhseet over the OLE automation interface (the PIA's are just shims over this) is a fairly heavyweight process. If you need to scale this to high data volumes you may need to be somewhat clever with your architecture.
Some of the 'use mime-types to trick excel into opening HTML table' approaches would work if you don't mind the format of the file being a bit basic. These approaches also fob the CPU heavy work off onto the client. If you want fine-graned control over the format of the spreadsheet you will probably have to use Excel itself to generate the file as described above.
发布评论
评论(26)
我推荐免费的开源Excel生成库,它是基于OpenXML的,
它在几个月前帮助了我。
I recommend free opensource excel generation libruary which is based on OpenXML
It helped me several months ago.
这是从存储过程中提取的报告。 结果导出至 Excel。
它使用 ADO 而不是 ADO.NET,原因是这一行
它完成了大部分工作,但在 ado.net 中不可用。
Here's a report that pulls from a stored procedure. The results are exported to Excel.
It uses ADO instead of ADO.NET and the reason why is this line
It does most of the work and isn't available in ado.net.
我只会根据数据创建一个 CSV 文件,因为我认为这是最干净的,并且 Excel 对其有很好的支持。 但如果您需要更灵活的格式,我确信有一些第三方工具可以生成真正的 Excel 文件。
I would just create a CSV file based on the data, because I see that as the cleanest, and Excel has good support for it. But if you require a more flexible format, I'm sure there's some 3rd party tools for generating real excel files.
这是一个将数据表以 CSV 形式输出的解决方案。 快速、干净、简单,并且它可以处理输入中的逗号。
Here's a solution the streams the datatable out as a CSV. Fast, clean, and easy, and it handles commas in the input.
我使用上面建议的解决方案之一遇到的问题之一类似于 这个答案是,如果您将内容作为附件推送出来(我发现这是非 MS 浏览器最干净的解决方案),然后打开它在 Excel 2000-2003 中,其类型是“Excel 网页”,而不是本机 Excel 文档。
然后,您必须向用户解释如何使用 Excel 中的“另存为类型”将其转换为 Excel 文档。 如果用户需要编辑此文档然后将其重新上传到您的网站,这将是一件痛苦的事情。
我的建议是使用 CSV。 它很简单,如果用户确实从 Excel 中打开它,Excel 至少会提示他们将其保存为其本机格式。
One of the problems I've ran across using one of the solutions suggested above which are similar to this answer is that if you push the content out as an attachment (what I've found to be the cleanest solution for non-ms browsers), then open it in Excel 2000-2003, its type is an "Excel Web Page" and not a native Excel document.
Then you have to explain to users how to use "Save as type" from within Excel to convert it to an Excel document. This is a pain if users need to edit this document and then re-upload it to your site.
My recommendation is to use CSV. It's simple and if users do open it from within Excel, Excel at least prompts them to save it in its native format.
假设这是针对 Intranet,您可以在其中设置权限并强制 IE,则可以使用 生成工作簿客户端JScript/VBScript 驱动 Excel。 这为您提供了本机 Excel 格式设置,无需尝试在服务器上自动化 Excel 的麻烦。
我不确定我是否真的会再推荐这种方法,除非是在相当小众的场景中,但它在经典 ASP 的鼎盛时期相当常见。
Assuming this is for an intranet, where you can set permissions and mandate IE, you can generate the workbook client side with JScript/VBScript driving Excel. This gives you native Excel formatting, without the hassle of trying to automate Excel on the server.
I'm not sure I'd really recommend this approach anymore except in fairly niche scenarios, but it was fairly common during the classic ASP heydays.
CSV
优点:
缺点:
HTML
优点:
缺点:
OpenXML (Office 2007 .XLSX)
优点:
缺点:
SpreadSheetML(开放格式 XML),
很复杂优点:
缺点:
XLS(由第三方组件生成)
优点:
缺点:
COM Interop
优点:
缺点:
CSV
Pros:
Cons:
HTML
Pros:
Cons:
OpenXML (Office 2007 .XLSX)
Pros:
Cons:
SpreadSheetML (open format XML)
Pros:
Cons:
XLS (generated by third party component)
Pros:
Cons:
COM Interop
Pros:
Cons:
您可以将数据输出为 html 表格单元格,在其上粘贴
.xls
或.xlsx
扩展名,Excel 将打开它,就像打开本机文档一样。 您甚至可以通过这种方式进行一些有限的格式化和公式计算,因此它比 CSV 强大得多。 此外,从像 ASP.Net 这样的 Web 平台输出 html 表格应该非常容易;)如果您需要在 Excel 工作簿中使用多个工作表或命名工作表,您可以通过名为
SpreadSheetML 的 XML 模式执行类似的操作
。 这不是随 Office 2007 一起提供的新格式,而是一种完全不同的格式,早在 Excel 2000 中就可以使用。解释其工作原理的最简单方法是使用一个示例:You can output the data as html table cells, stick a
.xls
or.xlsx
extension on it, and Excel will open it as if it were a native document. You can even do some limited formatting and formula calculations this way, so it's much more powerful than CSV. Also, outputting an html table ought to be pretty easy to do from a web platform like ASP.Net ;)If you need multiple worksheets or named worksheets within your Excel Workbook, you can do something similar via an XML schema called
SpreadSheetML
. This is not the new format that shipped with Office 2007, but something completely different that works as far back as Excel 2000. The easiest way to explain how it works is with an example:如果来自DataTable:
来自Gridview:
If coming from a DataTable:
From a Gridview:
根据给出的答案以及与同事的协商,最好的解决方案似乎是生成 XML 文件或 HTML 表格并将其作为附件推送下来。 我的同事建议的一项更改是数据(即 HTML 表)可以直接写入 Response 对象,从而消除了写出文件的需要,因为权限问题、I/O 问题可能会很麻烦。争用,并确保进行计划的清除。
这是代码片段...我还没有检查过这一点,也没有提供所有调用的代码,但我认为它很好地代表了这个想法。
Based on the answers given, and consultation with coworkers, it appears that the best solution is to generate either an XML file or HTML tables and push it down as an attachment. The one change recommended by my co-workers is that the data (i.e. the HTML tables) can be written directly to the Response object, thus eliminating the need to write out a file, which can be troublesome due to permissions problems, I/O contention, and ensuring that scheduled purging occurs.
Here's a snippet of the code... I haven't checked this yet, and I haven't supplied all the called code, but I think it represents the idea well.
由于 Excel 可以理解 HTML,因此您可以将数据作为 HTML 表写入扩展名为 .xls 的临时文件,获取该文件的 FileInfo,然后使用将其吹回,
如果您想避免临时文件,则可以写入 如果省略了内容长度标头,则可以直接将 html 写回内存中流并写回字节,而不是使用 WriteFile
,但这可能无法在所有浏览器中始终正常工作
since Excel understands HTML you can just write the data out as an HTML table to a temp file with an .xls extension, get the FileInfo for the file, and blow it back using
if you wanted to avoid the temp file, you could write to an in-memory stream and write the bytes back instead of using WriteFile
if the content-length header is omitted you could just write the html back directly, but this may not work correctly all the time in all browsers
我个人更喜欢XML方法。 我将从数据集中返回数据库中的数据,将其保存到 XMl,然后创建一个 xslt 文件,其中包含将格式化正确文档的转换规则,并且简单的 XML 转换将完成该工作。 最好的部分是您可以设置单元格格式、条件格式、设置页眉和页脚,甚至设置打印范围。
I personally prefer the XML method. I'll return the data from the database in a Dataset, save it to XMl, then I create an xslt file that contains a transformation rule that will format a proper document, and a simple XML transform will finish the job up. The best part of about this you can format cells, do conditional formatting, setup headers and footers, and even set print ranges.
我已经这样做过几次,每次最简单的方法就是简单地返回 CSV(逗号分隔值)文件。 Excel 可以完美导入它,而且速度相对较快。
I've done this a couple of times and each time the easiest way was to simply return a CSV (Comma Separated Value) file. Excel imports it perfectly, and it's relatively fast to do.
我们一直将数据从数据网格导出到 Excel。 将其转换为 HTML,然后写入 Excel 文件
这种方法的唯一问题是,我们的许多网格中都有按钮或链接,因此您也需要这个:
我发现在某个地方,它运行良好。
we export data from a datagrid to excel all the time. Converting it to HTML then writing to an excel file
The only gotcha with this method was that a lot of our grids had buttons or links in them so you need this too:
I found that somewhere, it works well.
这是 SpreadML 的免费包装——它效果很好。
http://www.carlosag.net/Tools/ExcelXmlWriter/
This is a free wrapper around SpreadML--it works great.
http://www.carlosag.net/Tools/ExcelXmlWriter/
如果您用数据填充 GridView,则可以使用此函数获取 HTML 格式的数据,但会向浏览器指示它是一个 Excel 文件。
If you fill a GridView with data you can use this function to get the HTML formatted data, but indicating the browser it's an excel file.
只需避免通过 Microsoft.Office.Interop 命名空间进行 COM Interop 即可。 它是如此缓慢、不可靠、不可扩展。 不适用于受虐狂。
Just avoid COM Interop via Microsoft.Office.Interop namespace. It is so damn slow and unreliable and unscalable. Not applicable for masochists.
您可以使用此库轻松创建格式良好的 Excel 文件:http://officehelper.codeplex.com/documentation。
网络服务器上不需要安装 Microsoft Office!
You can create nicely formatted Excel files using this library, quite easily: http://officehelper.codeplex.com/documentation.
Microsoft Office does not need to be installed on the webserver!
CSV 是最简单的方法。 大多数时候它与 Excel 链接。 否则,您必须使用自动化 API 或 XML 格式。 API 和 XML 并不难使用。
有关为 Excel 生成 XML 的信息
CSV is easiest way. Most of the time it is linked to Excel. Otherwise you have to use the automation APIs or XML format. The APIs and XML are not that hard to use.
Information about generating XML for Excel
我要么采用 CSV 路线(如上所述),要么现在更经常使用 Infragistics NetAdvantage 来生成文件。 (Infragistics 发挥作用的绝大多数时间,我们只是导出现有的 UltraWebGrid,这本质上是一个单 LOC 解决方案,除非需要额外的格式调整。我们也可以手动生成 Excel/BIFF 文件,但很少有必要。)
I either go the CSV route (as described above), or more often these days, I use Infragistics NetAdvantage to generate the file. (The very vast majority of the time where Infragistics is in play, we're just exporting an existing UltraWebGrid, which is essentially a one-LOC solution unless extra formatting tweaks are needed. We could manually generate an Excel/BIFF file as well, but there's rarely a need to.)
伙计,在.net中我想你可以有一个组件可以做到这一点,但是在经典的asp中我已经完成了创建一个html表并将页面的mimetipe更改为vnd/msexcel。 我想如果你使用 gridview 并更改 mime 类型也许它应该可以工作,因为 gridview 是一个 html 表。
man, in .net i guess you could have a component that could do that, but in classic asp I have already done it creating an html table and changing the mime tipe of the page to vnd/msexcel. I guess that if you use a gridview and change the mime type maybe it should work, because the gridview is an html table.
避免“看起来这些数字存储为文本”绿色三角形的唯一万无一失的方法是使用 Open XML 格式。 值得使用它,只是为了避免不可避免的绿色三角形。
The only bulletproof way of avoiding the "It looks like these numbers are stored as text" green triangles is to use the Open XML format. It is worth using it, just to avoid the inevitable green triangles.
我见过的 Excel 报告的最佳方法是使用 XML 扩展以 XML 格式写出数据,并将其以正确的内容类型流式传输到客户端。 (应用程序/xls)
这适用于任何需要基本格式的报告,并允许您使用文本比较工具与现有电子表格进行比较。
The best method i've seen for excel reports is to write out the data in XML with a XML extension and stream it to clients with the correct content type. (application/xls)
This works for any report which requires basic formating, and allows you to compare against existing spreadsheets by using text comparison tools.
当然,您始终可以选择第三方组件。 就我个人而言,我在 Spire.XLS http://www.e- Iceblue.com/xls/xlsintro.htm
该组件在您的应用程序中非常易于使用:
You can of course always go for a third party components. Personally, I have had a good experience with Spire.XLS http://www.e-iceblue.com/xls/xlsintro.htm
The component is pretty easy to use within your application:
刚刚创建了一个从 Web 表单 C# 导出到 Excel 的函数,希望对其他人有帮助
just created a function to export from a web form C# to excel hope it helps others
如果必须使用 Excel 而不是 CSV 文件,则需要在服务器之一的 Excel 实例上使用 OLE 自动化。 最简单的方法是拥有一个模板文件并以编程方式填充数据。 您将其保存到另一个文件中。
提示:
如果您不介意文件格式有点基本,那么某些“使用 mime 类型诱骗 excel 打开 HTML 表”方法就可以使用。 这些方法还将 CPU 的繁重工作转移到客户端上。 如果您想要对电子表格的格式进行精细控制,您可能必须使用 Excel 本身来生成如上所述的文件。
If you have to use Excel instead of a CSV file you will need to use OLE automation on an Excel instance one the server. The easiest way to do this is to have a template file and programatically fill it in with the data. You save it to another file.
Tips:
Some of the 'use mime-types to trick excel into opening HTML table' approaches would work if you don't mind the format of the file being a bit basic. These approaches also fob the CPU heavy work off onto the client. If you want fine-graned control over the format of the spreadsheet you will probably have to use Excel itself to generate the file as described above.