第一种:服务端需要装EXCEL <% Option Explicit Class ExcelGen Private objSpreadsheet Private iColOffset Private iRowOffset Sub Class_Initialize() Set objSpreadsheet = Server.CreateObject("OWC.Spreadsheet") iRowOffset = 2 iColOffset = 2 End Sub Sub Class_Terminate() Set objSpreadsheet = Nothing 'Clean up End Sub Public Property Let ColumnOffset(iColOff) If iColOff > 0 then iColOffset = iColOff Else iColOffset = 2 End If End Property Public Property Let RowOffset(iRowOff) If iRowOff > 0 then iRowOffset = iRowOff Else iRowOffset = 2 End If End Property Sub GenerateWorksheet(objRS) 'Populates the Excel worksheet based on a Recordset's contents 'Start by displaying the titles If objRS.EOF then Exit Sub Dim objField, iCol, iRow iCol = iColOffset iRow = iRowOffset For Each objField in objRS.Fields objSpreadsheet.Cells(iRow, iCol).Value = objField.Name objSpreadsheet.Columns(iCol).AutoFitColumns '设置Excel表里的字体 objSpreadsheet.Cells(iRow, iCol).Font.Bold = True objSpreadsheet.Cells(iRow, iCol).Font.Italic = False objSpreadsheet.Cells(iRow, iCol).Font.Size = 10 objSpreadsheet.Cells(iRow, iCol).Halignment = 2 '居中 iCol = iCol + 1 Next 'objField 'Display all of the data Do While Not objRS.EOF iRow = iRow + 1 iCol = iColOffset For Each objField in objRS.Fields If IsNull(objField.Value) then objSpreadsheet.Cells(iRow, iCol).Value = "" Else objSpreadsheet.Cells(iRow, iCol).Value = objField.Value objSpreadsheet.Columns(iCol).AutoFitColumns objSpreadsheet.Cells(iRow, iCol).Font.Bold = False objSpreadsheet.Cells(iRow, iCol).Font.Italic = False objSpreadsheet.Cells(iRow, iCol).Font.Size = 10 End If iCol = iCol + 1 Next 'objField objRS.MoveNext Loop End Sub Function SaveWorksheet(strFileName) 'Save the worksheet to a specified filename On Error Resume Next Call objSpreadsheet.ActiveSheet.Export(strFileName, 0) SaveWorksheet = (Err.Number = 0) End Function End Class Dim objRS Set objRS = Server.CreateObject("ADODB.Recordset") objRS.Open "Select top 100 * from customers","DRIVER={SQL SERVER};SERVER=get04c0038;UID=sa;PWD=xthvj;DATABASE=Northwind;" Dim SaveName SaveName = Request.Cookies("savename")("name") Dim objExcel Dim ExcelPath ExcelPath = "Excel\" & SaveName & ".xls" Set objExcel = New ExcelGen objExcel.RowOffset = 1 objExcel.ColumnOffset = 1 objExcel.GenerateWorksheet(objRS) If objExcel.SaveWorksheet(Server.MapPath(ExcelPath)) then Response.Write "<html><body bgcolor='gainsboro' text='#000000'>已保存为Excel文件. <a href='" & server.URLEncode(ExcelPath) & "'>下载</a>" Else Response.Write "在保存过程中有错误!" End If Set objExcel = Nothing objRS.Close Set objRS = Nothing %>
概要 本文介绍如何使用 Visual C# .NET 通过 ASP.NET (.aspx) 页显示 Excel 工作表中的数据。返回页首创建示例 Excel 工作表 1. 启动 Microsoft Excel,然后创建一个新的工作表。 2. 将以下信息添加到新工作表中以创建一个简单的 Excel 数据库: A B 1 FirstName LastName 2 Scott Bishop 3 Katie Jordan 注意:虽然在本示例中数据是从单元格 A1 开始的,但是您可以将此数据添加到工作表中的任何相邻接的单元格。 3. 突出显示此数据所在的行和列。 4. 在插入菜单上,指向名称,然后单击定义。 5. 在“当前工作簿中的名称”文本框中,键入 myRange1,然后单击确定。 6. 在文件菜单上,单击保存。在“保存位置”列表中,选择 Web 服务器的根目录(通常为 C:\InetPub\Wwwroot\)。在“文件名”文本框中,键入 ExcelData.xls。单击确定。 7. 在文件菜单上,单击退出。 返回页首使用 Visual C# .NET 创建 ASP.NET 示例 此代码示例说明如何查询和显示 Excel 工作表中的信息。以下代码使用您在上一节中创建的工作表。 1. 打开 Microsoft Visual Studio .NET。此时将显示 Visual Studio .NET 集成开发环境 (IDE)。 2. 在文件菜单上,指向新建,然后单击项目。 3. 在新建项目对话框的项目类型下面,单击 Visual C# 项目。在模板下面,单击 ASP.NET Web 应用程序。 4. 在新建项目对话框中,找到名称和位置文本框。注意,名称文本框不可用(它显示为灰色)。位置文本框包含以下文本(或类似的文本): http://localhost/WebApplication1 将位置文本框中的文本替换为 http://localhost/ExcelCSTest,然后单击确定。此时将创建一个新项目,其中包括一个名为 WebForm1.aspx 的 Web 窗体。 5. 在 Visual Studio .NET IDE 中,找到“解决方案资源管理器”窗口。如果找不到该窗口,请单击视图菜单上的解决方案资源管理器。 6. 在解决方案资源管理器中,右键单击 WebForm1.aspx,然后单击视图设计器以显示用于设计页面外观的设计器。可以使用该设计器,添加控件并处理页面的外观。 7. 查找工具箱。根据您的“IDE 选项”设置,工具箱可能以窗口或按钮的形式出现(通常出现在 IDE 的左侧)。如果找不到工具箱,请单击视图菜单上的工具箱。如果工具箱以按钮的形式出现,将指针移动到该按钮上以显示工具箱的内容。 8. 当 Web 窗体的设计器视图处于活动状态时,工具箱被划分为几部分,其中包括 Web 窗体、组件、HTML 和其他部分。单击 Web 窗体部分。 9. 在工具箱的 Web 窗体部分,单击 DataGrid,然后将其拖到 WebForm1 的设计器上。 10. 右键单击 WebForm1.aspx,然后单击查看代码以显示代码隐藏页的源代码。 11. 将下面的语句添加到代码隐藏页顶部的命名空间部分之上:using System.Data.OleDb; using System.Data;
12. 突出显示以下代码,右键单击该代码,然后单击复制。在 WebForm1.aspx.cs 中,将这些代码复制到 Page_Load 事件中:// Create connection string variable. Modify the "Data Source" // parameter as appropriate for your environment. String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("../ExcelData.xls") + ";" + "Extended Properties=Excel 8.0;";// Create connection object by using the preceding connection string. OleDbConnection objConn = new OleDbConnection(sConnectionString);// Open connection with the database. objConn.Open();// The code to follow uses a SQL SELECT command to display the data from the worksheet.// Create new OleDbCommand to return data from worksheet. OleDbCommand objCmdSelect =new OleDbCommand("SELECT * FROM myRange1", objConn);// Create new OleDbDataAdapter that is used to build a DataSet // based on the preceding SQL SELECT statement. OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();// Pass the Select command to the adapter. objAdapter1.SelectCommand = objCmdSelect;// Create new DataSet to hold information from the worksheet. DataSet objDataset1 = new DataSet();// Fill the DataSet with the information from the worksheet. objAdapter1.Fill(objDataset1, "XLData");// Bind data to DataGrid control. DataGrid1.DataSource = objDataset1.Tables[0].DefaultView; DataGrid1.DataBind();// Clean up objects. objConn.Close();
13. 在文件菜单中,单击全部保存来保存项目文件。 14. 在生成菜单上,单击生成以生成项目。这就准备好了代码隐藏页中的代码,使之能够执行了。 15. 在解决方案资源管理器中,右键单击 WebForm1.aspx,然后单击在浏览器中查看以运行代码。 返回页首其他代码说明 本文中的示例代码使用 Microsoft Jet OLE DB 提供程序访问 Excel 工作表。此代码使用以下连接字符串连接到工作表: // Create connection string variable. Modify the "Data Source" // parameter as appropriate for your environment. String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("../ExcelData.xls") + ";" + "Extended Properties=Excel 8.0;";
正如注释中所描述的那样,必须修改特定 Excel 工作表的路径信息。此外,还必须设置 Extended Properties 参数的值,以便正确地连接到文件。注意,连接字符串使用 Server.MapPath 函数。此函数使用文件相对于 Microsoft Internet 信息服务 (IIS) 的路径,并返回该文件的硬盘路径。例如,在创建示例 Excel 工作表 部分中,您在 Web 根目录中创建了 ExcelData.xls,该目录通常位于 C:\Inetpub\Wwwroot。这还会在 Wwwroot 文件夹中创建名为 ExcelCSTest 的子文件夹,并在 ExcelCSTest 文件夹中创建名为 WebForm1.aspx 的文件。在此示例中,硬盘上的文件路径如下: C 驱动器 - Inetpub - Wwwroot(其中包含 ExcelData.xls) - ExcelCSTest(包含 WebForm1.aspx)
文件的 IIS 路径如下所示: Web 根目录(其中包含 ExcelData.xls) - ExcelCSTest(包含 WebForm1.aspx)
Response.Buffer= true;
Response.Charset="big5";
Response.AppendHeader("Content-Disposition","attachment;filename=FileFlow.xls");
Response.ContentEncoding=System.Text.Encoding.GetEncoding("big5");
Response.ContentType = "application/ms-excel";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
Microsoft Excel 10.0 Object Library
Microsoft Office 10.0 Object Library
然后参照这个
http://www.microsoft.com/china/msdn/library/office/office/UndstaExcelObjModNETDev.mspx
public static void KillProcess( string processName )
{
System.Diagnostics.Process myproc= new System.Diagnostics.Process();
try
{
foreach (Process thisproc in rocess.GetProcessesByName(processName))
{
if(!thisproc.CloseMainWindow())
{
thisproc.Kill();
}
}
}
catch(Exception err)
{
throw err;
}
}
这种方法是把打开的所有的Excel进程全部关闭
还有一种就是
ThisWorkbook.Close(false,Type.Missing,Type.Missing);
ThisApplication.Workbooks.Close();
ThisApplication.UserControl = false;
ThisApplication.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisWorksheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(NextWorksheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisWorkbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisApplication);
ThisWorksheet = null;
NextWorksheet = null;
ThisWorkbook = null;
ThisApplication = null;
System.GC.Collect();
不过这种方法我试过了,进程关不了
不过我在其中加上
在new ExcelApplication时加上
Process[] CurrentProcess ;
CurrentProcess = Process.GetProcessesByName("Excel");
int PId = 0;
if(CurrentProcess[0].Responding)
{
PId = CurrentProcess[0].Id;
}关闭的时候加上
Process ps = new Process();
ps = Process.GetProcessById(PId);
if(!ps.CloseMainWindow())
{
ps.Kill();
}这样的话,在进程里面就始终有一个Excel进程,不过已经是比较好的了
另外在webconfig里面设置
<identity impersonate="true"/> 基本上就可以了
<%
Option Explicit
Class ExcelGen
Private objSpreadsheet
Private iColOffset Private iRowOffset
Sub Class_Initialize()
Set objSpreadsheet = Server.CreateObject("OWC.Spreadsheet")
iRowOffset = 2
iColOffset = 2
End Sub Sub Class_Terminate()
Set objSpreadsheet = Nothing 'Clean up
End Sub Public Property Let ColumnOffset(iColOff)
If iColOff > 0 then
iColOffset = iColOff
Else
iColOffset = 2
End If
End Property Public Property Let RowOffset(iRowOff)
If iRowOff > 0 then
iRowOffset = iRowOff
Else
iRowOffset = 2
End If
End Property
Sub GenerateWorksheet(objRS)
'Populates the Excel worksheet based on a Recordset's contents
'Start by displaying the titles
If objRS.EOF then Exit Sub
Dim objField, iCol, iRow
iCol = iColOffset
iRow = iRowOffset
For Each objField in objRS.Fields
objSpreadsheet.Cells(iRow, iCol).Value = objField.Name
objSpreadsheet.Columns(iCol).AutoFitColumns
'设置Excel表里的字体
objSpreadsheet.Cells(iRow, iCol).Font.Bold = True
objSpreadsheet.Cells(iRow, iCol).Font.Italic = False
objSpreadsheet.Cells(iRow, iCol).Font.Size = 10
objSpreadsheet.Cells(iRow, iCol).Halignment = 2 '居中
iCol = iCol + 1
Next 'objField
'Display all of the data
Do While Not objRS.EOF
iRow = iRow + 1
iCol = iColOffset
For Each objField in objRS.Fields
If IsNull(objField.Value) then
objSpreadsheet.Cells(iRow, iCol).Value = ""
Else
objSpreadsheet.Cells(iRow, iCol).Value = objField.Value
objSpreadsheet.Columns(iCol).AutoFitColumns
objSpreadsheet.Cells(iRow, iCol).Font.Bold = False
objSpreadsheet.Cells(iRow, iCol).Font.Italic = False
objSpreadsheet.Cells(iRow, iCol).Font.Size = 10
End If
iCol = iCol + 1
Next 'objField
objRS.MoveNext
Loop
End Sub
Function SaveWorksheet(strFileName)
'Save the worksheet to a specified filename
On Error Resume Next
Call objSpreadsheet.ActiveSheet.Export(strFileName, 0)
SaveWorksheet = (Err.Number = 0)
End Function
End Class Dim objRS
Set objRS = Server.CreateObject("ADODB.Recordset")
objRS.Open "Select top 100 * from customers","DRIVER={SQL SERVER};SERVER=get04c0038;UID=sa;PWD=xthvj;DATABASE=Northwind;"
Dim SaveName
SaveName = Request.Cookies("savename")("name")
Dim objExcel
Dim ExcelPath
ExcelPath = "Excel\" & SaveName & ".xls"
Set objExcel = New ExcelGen
objExcel.RowOffset = 1
objExcel.ColumnOffset = 1
objExcel.GenerateWorksheet(objRS)
If objExcel.SaveWorksheet(Server.MapPath(ExcelPath)) then
Response.Write "<html><body bgcolor='gainsboro' text='#000000'>已保存为Excel文件. <a href='" & server.URLEncode(ExcelPath) & "'>下载</a>"
Else
Response.Write "在保存过程中有错误!"
End If
Set objExcel = Nothing
objRS.Close
Set objRS = Nothing
%>
<html>
<head>
<SCRIPT LANGUAGE="javascript">
<!--
//导出到Excel代码
function AutomateExcel()
{
// Start Excel and get Application object.
var oXL = new ActiveXObject("Excel.Application");
// Get a new workbook.
var oWB = oXL.Workbooks.Add();
var oSheet = oWB.ActiveSheet;
var table = document.all.Tabledata;
var hang = table.rows.length; var lie = table.rows(0).cells.length; // Add table headers going cell by cell.
for (i=0;i<hang;i++)
{
for (j=0;j<lie;j++)
{
oSheet.Cells(i+1,j+1).value = table.rows(i).cells(j).innerText;
} }
oXL.Visible = true;
oXL.UserControl = true;
}
//-->
</SCRIPT>
</head>
<body>
<TABLE id="Tabledata"
style="BORDER-RIGHT: #cc9966 1px; BORDER-TOP: #cc9966 1px; BORDER-LEFT: #cc9966 1px; WIDTH: 100%; BORDER-BOTTOM: #cc9966 1px; BORDER-COLLAPSE: collapse; BACKGROUND-COLOR: white"
borderColor=#cc9966 cellSpacing=0 cellPadding=4 rules=all border=1>
<TBODY>
<TR
style="FONT-WEIGHT: bold; FONT-SIZE: small; BORDER-LEFT-COLOR: mistyrose; BORDER-BOTTOM-COLOR: mistyrose; COLOR: black; BORDER-TOP-COLOR: mistyrose; FONT-FAMILY: 宋体; BACKGROUND-COLOR: lightpink; BORDER-RIGHT-COLOR: mistyrose"
vAlign=center align=middle>
<TD><font size="2">项目单号</font></TD>
<TD><font size="2">项目名称</font></TD>
<TD><font size="2">所属分厂</font></TD>
<TD><font size="2">部门</font></TD>
<TD><font size="2">成本中心</font></TD>
<TD><font size="2">立项日期</font></TD>
<TD><font size="2">合同编号</font></TD>
<TD><font size="2">合同金额</font></TD>
<TD><font size="2">计划开工日期</font></TD>
<TD><font size="2">计划完工日期</font></TD>
</TR>
<TR
style="FONT-SIZE: 12pt; COLOR: buttontext; FONT-FAMILY: 宋体; BACKGROUND-COLOR: white">
<TD><font size="2">44</font></TD>
<TD><font size="2">饭堂补漏工程 </font> </TD>
<TD><font size="2">SD </font> </TD>
<TD><font size="2">行政部 </font> </TD>
<TD><font size="2">359.910.1001 </font> </TD>
<TD><font size="2">2005-4-13 0:00:00</font></TD>
<TD><font size="2">fafas34 </font> </TD>
<TD><font size="2">12000</font></TD>
<TD><font size="2">2005-5-10 0:00:00</font></TD>
<TD><font size="2">2005-5-25 0:00:00</font></TD>
</TR>
<TR
style="FONT-SIZE: 12pt; COLOR: buttontext; FONT-FAMILY: 宋体; BACKGROUND-COLOR: white">
<TD><font size="2">46</font></TD>
<TD><font size="2">棉纺厂倍捻轴电气安装 </font> </TD>
<TD><font size="2">GES </font> </TD>
<TD><font size="2">GES-并捻(倍捻) </font> </TD>
<TD><font size="2">359.201.6011 </font> </TD>
<TD><font size="2">2003-8-1 0:00:00</font></TD>
<TD><font size="2">hhfghgfh </font> </TD>
<TD><font size="2">12000</font></TD>
<TD><font size="2">2005-5-25 0:00:00</font></TD>
<TD><font size="2">2005-5-27 0:00:00</font></TD>
</TR>
<TR
style="FONT-SIZE: 12pt; COLOR: buttontext; FONT-FAMILY: 宋体; BACKGROUND-COLOR: white">
<TD><font size="2">43</font></TD>
<TD><font size="2">GEK进出口改造 </font> </TD>
<TD><font size="2">GEK </font> </TD>
<TD><font size="2">GEK-进出口部 </font> </TD>
<TD><font size="2">359.401.2503 </font> </TD>
<TD><font size="2">2005-4-12 0:00:00</font></TD>
<TD><font size="2">get123 </font> </TD>
<TD><font size="2">12500</font></TD>
<TD><font size="2">2005-5-25 0:00:00</font></TD>
<TD><font size="2">2005-5-26 0:00:00</font></TD>
</TR>
<TR
style="FONT-SIZE: 12pt; COLOR: buttontext; FONT-FAMILY: 宋体; BACKGROUND-COLOR: white">
<TD><font size="2">42</font></TD>
<TD><font size="2">计划部改造 </font> </TD>
<TD><font size="2">GEK </font> </TD>
<TD><font size="2">GEK-计划部 </font> </TD>
<TD><font size="2">359.401.2001 </font> </TD>
<TD><font size="2">2005-4-12 0:00:00</font></TD>
<TD><font size="2">fgdfgdg </font> </TD>
<TD><font size="2">2000</font></TD>
<TD><font size="2">2005-5-31 0:00:00</font></TD>
<TD><font size="2">2005-5-25 0:00:00</font></TD>
</TR>
<TR
style="FONT-SIZE: 12pt; COLOR: buttontext; FONT-FAMILY: 宋体; BACKGROUND-COLOR: white">
<TD><font size="2">47</font></TD>
<TD><font size="2">test </font> </TD>
<TD><font size="2">GEK </font> </TD>
<TD><font size="2">GEK-外发部 </font> </TD>
<TD><font size="2">359.401.7006 </font> </TD>
<TD><font size="2">2005-5-26 0:00:00</font></TD>
<TD><font size="2">1gewr1323 </font> </TD>
<TD><font size="2">16000</font></TD>
<TD><font size="2">2005-5-18 0:00:00</font></TD>
<TD><font size="2">2005-5-20 0:00:00</font></TD>
</TR><input type="button" name="out_excel" onclick="AutomateExcel();" value="导出到excel" class="notPrint">
</body>
</html>
<html>
<head>
</head>
<body>
<TABLE id="Tabledata"
style="BORDER-RIGHT: #cc9966 1px; BORDER-TOP: #cc9966 1px; BORDER-LEFT: #cc9966 1px; WIDTH: 100%; BORDER-BOTTOM: #cc9966 1px; BORDER-COLLAPSE: collapse; BACKGROUND-COLOR: white"
borderColor=#cc9966 cellSpacing=0 cellPadding=4 rules=all border=1>
<TBODY>
<TR
style="FONT-WEIGHT: bold; FONT-SIZE: small; BORDER-LEFT-COLOR: mistyrose; BORDER-BOTTOM-COLOR: mistyrose; COLOR: black; BORDER-TOP-COLOR: mistyrose; FONT-FAMILY: 宋体; BACKGROUND-COLOR: lightpink; BORDER-RIGHT-COLOR: mistyrose"
vAlign=center align=middle>
<TD><font size="2">项目单号</font></TD>
<TD><font size="2">项目名称</font></TD>
<TD><font size="2">所属分厂</font></TD>
<TD><font size="2">部门</font></TD>
<TD><font size="2">成本中心</font></TD>
<TD><font size="2">立项日期</font></TD>
<TD><font size="2">合同编号</font></TD>
<TD><font size="2">合同金额</font></TD>
<TD><font size="2">计划开工日期</font></TD>
<TD><font size="2">计划完工日期</font></TD>
</TR>
<TR
style="FONT-SIZE: 12pt; COLOR: buttontext; FONT-FAMILY: 宋体; BACKGROUND-COLOR: white">
<TD><font size="2">44</font></TD>
<TD><font size="2">饭堂补漏工程 </font> </TD>
<TD><font size="2">SD </font> </TD>
<TD><font size="2">行政部 </font> </TD>
<TD><font size="2">359.910.1001 </font> </TD>
<TD><font size="2">2005-4-13 0:00:00</font></TD>
<TD><font size="2">fafas34 </font> </TD>
<TD><font size="2">12000</font></TD>
<TD><font size="2">2005-5-10 0:00:00</font></TD>
<TD><font size="2">2005-5-25 0:00:00</font></TD>
</TR>
<TR
style="FONT-SIZE: 12pt; COLOR: buttontext; FONT-FAMILY: 宋体; BACKGROUND-COLOR: white">
<TD><font size="2">46</font></TD>
<TD><font size="2">棉纺厂倍捻轴电气安装 </font> </TD>
<TD><font size="2">GES </font> </TD>
<TD><font size="2">GES-并捻(倍捻) </font> </TD>
<TD><font size="2">359.201.6011 </font> </TD>
<TD><font size="2">2003-8-1 0:00:00</font></TD>
<TD><font size="2">hhfghgfh </font> </TD>
<TD><font size="2">12000</font></TD>
<TD><font size="2">2005-5-25 0:00:00</font></TD>
<TD><font size="2">2005-5-27 0:00:00</font></TD>
</TR>
<TR
style="FONT-SIZE: 12pt; COLOR: buttontext; FONT-FAMILY: 宋体; BACKGROUND-COLOR: white">
<TD><font size="2">43</font></TD>
<TD><font size="2">GEK进出口改造 </font> </TD>
<TD><font size="2">GEK </font> </TD>
<TD><font size="2">GEK-进出口部 </font> </TD>
<TD><font size="2">359.401.2503 </font> </TD>
<TD><font size="2">2005-4-12 0:00:00</font></TD>
<TD><font size="2">get123 </font> </TD>
<TD><font size="2">12500</font></TD>
<TD><font size="2">2005-5-25 0:00:00</font></TD>
<TD><font size="2">2005-5-26 0:00:00</font></TD>
</TR>
<TR
style="FONT-SIZE: 12pt; COLOR: buttontext; FONT-FAMILY: 宋体; BACKGROUND-COLOR: white">
<TD><font size="2">42</font></TD>
<TD><font size="2">计划部改造 </font> </TD>
<TD><font size="2">GEK </font> </TD>
<TD><font size="2">GEK-计划部 </font> </TD>
<TD><font size="2">359.401.2001 </font> </TD>
<TD><font size="2">2005-4-12 0:00:00</font></TD>
<TD><font size="2">fgdfgdg </font> </TD>
<TD><font size="2">2000</font></TD>
<TD><font size="2">2005-5-31 0:00:00</font></TD>
<TD><font size="2">2005-5-25 0:00:00</font></TD>
</TR>
<TR
style="FONT-SIZE: 12pt; COLOR: buttontext; FONT-FAMILY: 宋体; BACKGROUND-COLOR: white">
<TD><font size="2">47</font></TD>
<TD><font size="2">test </font> </TD>
<TD><font size="2">GEK </font> </TD>
<TD><font size="2">GEK-外发部 </font> </TD>
<TD><font size="2">359.401.7006 </font> </TD>
<TD><font size="2">2005-5-26 0:00:00</font></TD>
<TD><font size="2">1gewr1323 </font> </TD>
<TD><font size="2">16000</font></TD>
<TD><font size="2">2005-5-18 0:00:00</font></TD>
<TD><font size="2">2005-5-20 0:00:00</font></TD>
</TR>
</table>
<%
Response.ContentType = "application/vnd.ms-excel"
Response.write("本页面出现下载对话框提供下载,保存类型为XLS")
%>
</body>
</html>
StringWriter sw=new StringWriter();
HtmlTextWriter htw=new HtmlTextWriter(sw);
DataGrid1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
htw.Close();
sw.Close();
本文介绍如何使用 Visual C# .NET 通过 ASP.NET (.aspx) 页显示 Excel 工作表中的数据。返回页首创建示例 Excel 工作表
1. 启动 Microsoft Excel,然后创建一个新的工作表。
2. 将以下信息添加到新工作表中以创建一个简单的 Excel 数据库:
A B
1 FirstName LastName
2 Scott Bishop
3 Katie Jordan
注意:虽然在本示例中数据是从单元格 A1 开始的,但是您可以将此数据添加到工作表中的任何相邻接的单元格。
3. 突出显示此数据所在的行和列。
4. 在插入菜单上,指向名称,然后单击定义。
5. 在“当前工作簿中的名称”文本框中,键入 myRange1,然后单击确定。
6. 在文件菜单上,单击保存。在“保存位置”列表中,选择 Web 服务器的根目录(通常为 C:\InetPub\Wwwroot\)。在“文件名”文本框中,键入 ExcelData.xls。单击确定。
7. 在文件菜单上,单击退出。
返回页首使用 Visual C# .NET 创建 ASP.NET 示例
此代码示例说明如何查询和显示 Excel 工作表中的信息。以下代码使用您在上一节中创建的工作表。 1. 打开 Microsoft Visual Studio .NET。此时将显示 Visual Studio .NET 集成开发环境 (IDE)。
2. 在文件菜单上,指向新建,然后单击项目。
3. 在新建项目对话框的项目类型下面,单击 Visual C# 项目。在模板下面,单击 ASP.NET Web 应用程序。
4. 在新建项目对话框中,找到名称和位置文本框。注意,名称文本框不可用(它显示为灰色)。位置文本框包含以下文本(或类似的文本):
http://localhost/WebApplication1
将位置文本框中的文本替换为 http://localhost/ExcelCSTest,然后单击确定。此时将创建一个新项目,其中包括一个名为 WebForm1.aspx 的 Web 窗体。
5. 在 Visual Studio .NET IDE 中,找到“解决方案资源管理器”窗口。如果找不到该窗口,请单击视图菜单上的解决方案资源管理器。
6. 在解决方案资源管理器中,右键单击 WebForm1.aspx,然后单击视图设计器以显示用于设计页面外观的设计器。可以使用该设计器,添加控件并处理页面的外观。
7. 查找工具箱。根据您的“IDE 选项”设置,工具箱可能以窗口或按钮的形式出现(通常出现在 IDE 的左侧)。如果找不到工具箱,请单击视图菜单上的工具箱。如果工具箱以按钮的形式出现,将指针移动到该按钮上以显示工具箱的内容。
8. 当 Web 窗体的设计器视图处于活动状态时,工具箱被划分为几部分,其中包括 Web 窗体、组件、HTML 和其他部分。单击 Web 窗体部分。
9. 在工具箱的 Web 窗体部分,单击 DataGrid,然后将其拖到 WebForm1 的设计器上。
10. 右键单击 WebForm1.aspx,然后单击查看代码以显示代码隐藏页的源代码。
11. 将下面的语句添加到代码隐藏页顶部的命名空间部分之上:using System.Data.OleDb;
using System.Data;
12. 突出显示以下代码,右键单击该代码,然后单击复制。在 WebForm1.aspx.cs 中,将这些代码复制到 Page_Load 事件中:// Create connection string variable. Modify the "Data Source"
// parameter as appropriate for your environment.
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Server.MapPath("../ExcelData.xls") + ";" +
"Extended Properties=Excel 8.0;";// Create connection object by using the preceding connection string.
OleDbConnection objConn = new OleDbConnection(sConnectionString);// Open connection with the database.
objConn.Open();// The code to follow uses a SQL SELECT command to display the data from the worksheet.// Create new OleDbCommand to return data from worksheet.
OleDbCommand objCmdSelect =new OleDbCommand("SELECT * FROM myRange1", objConn);// Create new OleDbDataAdapter that is used to build a DataSet
// based on the preceding SQL SELECT statement.
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();// Pass the Select command to the adapter.
objAdapter1.SelectCommand = objCmdSelect;// Create new DataSet to hold information from the worksheet.
DataSet objDataset1 = new DataSet();// Fill the DataSet with the information from the worksheet.
objAdapter1.Fill(objDataset1, "XLData");// Bind data to DataGrid control.
DataGrid1.DataSource = objDataset1.Tables[0].DefaultView;
DataGrid1.DataBind();// Clean up objects.
objConn.Close();
13. 在文件菜单中,单击全部保存来保存项目文件。
14. 在生成菜单上,单击生成以生成项目。这就准备好了代码隐藏页中的代码,使之能够执行了。
15. 在解决方案资源管理器中,右键单击 WebForm1.aspx,然后单击在浏览器中查看以运行代码。
返回页首其他代码说明
本文中的示例代码使用 Microsoft Jet OLE DB 提供程序访问 Excel 工作表。此代码使用以下连接字符串连接到工作表: // Create connection string variable. Modify the "Data Source"
// parameter as appropriate for your environment.
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Server.MapPath("../ExcelData.xls") + ";" +
"Extended Properties=Excel 8.0;";
正如注释中所描述的那样,必须修改特定 Excel 工作表的路径信息。此外,还必须设置 Extended Properties 参数的值,以便正确地连接到文件。注意,连接字符串使用 Server.MapPath 函数。此函数使用文件相对于 Microsoft Internet 信息服务 (IIS) 的路径,并返回该文件的硬盘路径。例如,在创建示例 Excel 工作表 部分中,您在 Web 根目录中创建了 ExcelData.xls,该目录通常位于 C:\Inetpub\Wwwroot。这还会在 Wwwroot 文件夹中创建名为 ExcelCSTest 的子文件夹,并在 ExcelCSTest 文件夹中创建名为 WebForm1.aspx 的文件。在此示例中,硬盘上的文件路径如下: C 驱动器
- Inetpub
- Wwwroot(其中包含 ExcelData.xls)
- ExcelCSTest(包含 WebForm1.aspx)
文件的 IIS 路径如下所示: Web 根目录(其中包含 ExcelData.xls)
- ExcelCSTest(包含 WebForm1.aspx)
在本例中,WebForm1.aspx 页到 ExcelData.xls 文件的相对 路径为“../ExcelData.xls”。“../”字符通知 IIS 转到上一级文件夹。因此,代码 Server.MapPath("../ExcelData.xls")
返回以下字符串:
C:\Inetpub\Wwwroot\ExcelData.xls
您无需使用 Server.MapPath。您也可以将此信息硬编码为一个特定的路径,或使用任何方法提供该 Excel 文件在硬盘上的位置。
StringWriter sw=new StringWriter();
HtmlTextWriter htw=new HtmlTextWriter(sw);
DataGrid1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
htw.Close();
sw.Close();