参考《Windows脚本技术》,应该会有一点收获。
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
</head>
<script language="javascript" type="text/javascript">
function importXLS(fileName)
{
objCon = new ActiveXObject("ADODB.Connection")
objCon.Provider = "Microsoft.Jet.OLEDB.4.0"
objCon.ConnectionString = "Data Source=" + fileName + "Extended Properties=Excel 8.0"
objCon.CursorLocation = 1
objCon.Open
var strQuery
//Get the SheetName
var strSheetName = "Sheet1$"
var rsTemp = new ActiveXObject("ADODB.Recordset")
rsTemp = objCon.OpenSchema(20)
if(!rsTemp.EOF)
strSheetName = rsTemp.Fields("Table_Name").Value
rsTemp = null
rsExcel = new ActiveXObject("ADODB.Recordset")
strQuery = "SELECT * FROM [" + strSheetName + "]"
rsExcel.ActiveConnection = objCon
rsExcel.Open(strQuery)
while(!rsExcel.EOF)
{
for(i = 0i<rsExcel.Fields.Count++i)
{
alert(rsExcel.Fields(i).value)
}
rsExcel.MoveNext
}
// Close the connection and dispose the file
objCon.Close
objCon =null
rsExcel = null
}
</script>
</head>
<body>
<input type="file" id="f" />
<input type="button" id="b" value="import" onclick="if(f.value=='')alert('请选择xls文件')else importXLS(f.value)" />
</body>
</html>
trackback:http://hi.baidu.com/netcorner/blog/item/4c35a818788f670635fa41d3.html
通过Javascript操作Excel
function AutomateExcel()
{
// Start Excel and get Application object.
var oXL = new ActiveXObject("Excel.Application")
oXL.Visible = true
// Get a new workbook.
var oWB = oXL.Workbooks.Add()
var oSheet = oWB.ActiveSheet
// Add table headers going cell by cell.
oSheet.Cells(1, 1).Value = "First Name"
oSheet.Cells(1, 2).Value = "Last Name"
oSheet.Cells(1, 3).Value = "Full Name"
oSheet.Cells(1, 4).Value = "Salary"
// Format A1:D1 as bold, vertical alignment = center.
oSheet.Range("A1", "D1").Font.Bold = true
oSheet.Range("A1", "D1").VerticalAlignment = -4108 //xlVAlignCenter
// Create an array to set multiple values at once.
// Fill A2:B6 with an array of values (from VBScript).
oSheet.Range("A2", "B6").Value = CreateNamesArray()
// Fill C2:C6 with a relative formula (=A2 & " " & B2).
var oRng = oSheet.Range("C2", "C6")
oRng.Formula = "=A2 & " " & B2"
// Fill D2:D6 with a formula(=RAND()*100000) and apply format.
oRng = oSheet.Range("D2", "D6")
oRng.Formula = "=RAND()*100000"
oRng.NumberFormat = "$0.00"
// AutoFit columns A:D.
oRng = oSheet.Range("A1", "D1")
oRng.EntireColumn.AutoFit()
// Manipulate a variable number of columns for Quarterly Sales Data.
DispalyQuarterlySales(oSheet)
// Make sure Excel is visible and give the user control
// of Excel's lifetime.
oXL.Visible = true
oXL.UserControl = true
}
<HTML>
<HEAD>
<TITLE>将页面中指定表格的数据导入到Excel中</TITLE>
<SCRIPT LANGUAGE="javascript">
<!--
function AutomateExcel()
{
var oXL = new ActiveXObject("Excel.Application")//创建应该对象
var oWB = oXL.Workbooks.Add()//新建一个Excel工作簿
var oSheet = oWB.ActiveSheet//指定要写入内容的工作表为活动工作表
var table = document.all.data//指定要写入的数据源的id
var hang = table.rows.length//取数据源行数
var lie = table.rows(0).cells.length//取数据源列数
// Add table headers going cell by cell.
for (i=0i<hangi++){//在Excel中写行
for (j=0j<liej++){//在Excel中写列
//定义格式
oSheet.Cells(i+1,j+1).NumberFormatLocal = "@"
//!!!!!!!上面这一句是将单元格的格式定义为文本
oSheet.Cells(i+1,j+1).Font.Bold = true//加粗
oSheet.Cells(i+1,j+1).Font.Size = 10//字体大小
oSheet.Cells(i+1,j+1).value = table.rows(i).cells(j).innerText//向单元格写入值
}
}
oXL.Visible = true
oXL.UserControl = true
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<table border="0" width="300" id="data" bgcolor="black" cellspacing="1">
<tr bgcolor="white">
<td>编号</td>
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
</tr>
<tr bgcolor="white">
<td>0001</td>
<td>张三</td>
<td>22</td>
<td>女</td>
</tr>
<tr bgcolor="white">
<td>0002</td>
<td>李四</td>
<td>23</td>
<td>男</td>
</tr>
</table>
<input type="button" name="out_excel" onclick="AutomateExcel()" value="导出到excel">
</BODY>
</HTML>
以前读书的时候绝不会想到会用客户端脚本来实现这些功能,现在却一开始就要用上了,而且还觉得挺实用的。
参考《Windows脚本技术》,应该会有一点收获。
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
</head>
<script language="javascript" type="text/javascript">
function importXLS(fileName)
{
objCon = new ActiveXObject("ADODB.Connection")
objCon.Provider = "Microsoft.Jet.OLEDB.4.0"
objCon.ConnectionString = "Data Source=" + fileName + "Extended Properties=Excel 8.0"
objCon.CursorLocation = 1
objCon.Open
var strQuery
//Get the SheetName
var strSheetName = "Sheet1$"
var rsTemp = new ActiveXObject("ADODB.Recordset")
rsTemp = objCon.OpenSchema(20)
if(!rsTemp.EOF)
strSheetName = rsTemp.Fields("Table_Name").Value
rsTemp = null
rsExcel = new ActiveXObject("ADODB.Recordset")
strQuery = "SELECT * FROM [" + strSheetName + "]"
rsExcel.ActiveConnection = objCon
rsExcel.Open(strQuery)
while(!rsExcel.EOF)
{
for(i = 0i<rsExcel.Fields.Count++i)
{
alert(rsExcel.Fields(i).value)
}
rsExcel.MoveNext
}
// Close the connection and dispose the file
objCon.Close
objCon =null
rsExcel = null
}
</script>
</head>
<body>
<input type="file" id="f" />
<input type="button" id="b" value="import" onclick="if(f.value=='')alert('请选择xls文件')else importXLS(f.value)" />
</body>
</html>
trackback:http://hi.baidu.com/netcorner/blog/item/4c35a818788f670635fa41d3.html
通过Javascript操作Excel
function AutomateExcel()
{
// Start Excel and get Application object.
var oXL = new ActiveXObject("Excel.Application")
oXL.Visible = true
// Get a new workbook.
var oWB = oXL.Workbooks.Add()
var oSheet = oWB.ActiveSheet
// Add table headers going cell by cell.
oSheet.Cells(1, 1).Value = "First Name"
oSheet.Cells(1, 2).Value = "Last Name"
oSheet.Cells(1, 3).Value = "Full Name"
oSheet.Cells(1, 4).Value = "Salary"
// Format A1:D1 as bold, vertical alignment = center.
oSheet.Range("A1", "D1").Font.Bold = true
oSheet.Range("A1", "D1").VerticalAlignment = -4108 //xlVAlignCenter
// Create an array to set multiple values at once.
// Fill A2:B6 with an array of values (from VBScript).
oSheet.Range("A2", "B6").Value = CreateNamesArray()
// Fill C2:C6 with a relative formula (=A2 & " " & B2).
var oRng = oSheet.Range("C2", "C6")
oRng.Formula = "=A2 & " " & B2"
// Fill D2:D6 with a formula(=RAND()*100000) and apply format.
oRng = oSheet.Range("D2", "D6")
oRng.Formula = "=RAND()*100000"
oRng.NumberFormat = "$0.00"
// AutoFit columns A:D.
oRng = oSheet.Range("A1", "D1")
oRng.EntireColumn.AutoFit()
// Manipulate a variable number of columns for Quarterly Sales Data.
DispalyQuarterlySales(oSheet)
// Make sure Excel is visible and give the user control
// of Excel's lifetime.
oXL.Visible = true
oXL.UserControl = true
}
<HTML>
<HEAD>
<TITLE>将页面中指定表格的数据导入到Excel中</TITLE>
<SCRIPT LANGUAGE="javascript">
<!--
function AutomateExcel()
{
var oXL = new ActiveXObject("Excel.Application")//创建应该对象
var oWB = oXL.Workbooks.Add()//新建一个Excel工作簿
var oSheet = oWB.ActiveSheet//指定要写入内容的工作表为活动工作表
var table = document.all.data//指定要写入的数据源的id
var hang = table.rows.length//取数据源行数
var lie = table.rows(0).cells.length//取数据源列数
// Add table headers going cell by cell.
for (i=0i<hangi++){//在Excel中写行
for (j=0j<liej++){//在Excel中写列
//定义格式
oSheet.Cells(i+1,j+1).NumberFormatLocal = "@"
//!!!!!!!上面这一句是将单元格的格式定义为文本
oSheet.Cells(i+1,j+1).Font.Bold = true//加粗
oSheet.Cells(i+1,j+1).Font.Size = 10//字体大小
oSheet.Cells(i+1,j+1).value = table.rows(i).cells(j).innerText//向单元格写入值
}
}
oXL.Visible = true
oXL.UserControl = true
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<table border="0" width="300" id="data" bgcolor="black" cellspacing="1">
<tr bgcolor="white">
<td>编号</td>
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
</tr>
<tr bgcolor="white">
<td>0001</td>
<td>张三</td>
<td>22</td>
<td>女</td>
</tr>
<tr bgcolor="white">
<td>0002</td>
<td>李四</td>
<td>23</td>
<td>男</td>
</tr>
</table>
<input type="button" name="out_excel" onclick="AutomateExcel()" value="导出到excel">
</BODY>
</HTML>
1. 要正确的将Web客户端的Excel文件导入到服务器的数据库中,需要将客户端的Excel文件上传到服务器上。可以使用FileUpload控件完成。2. Excel文件上传到服务器指定的目录中,这里假设是该站点的upfiles目录中。
3. 使用SQL语句从upfiles目录中的上传Excel文件中读取数据显示或写入数据库。
相关代码如下:
1. 前台文件:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="StudentInforInport.aspx.cs" Inherits="StudentInforInport" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<title>从Excel表中导入学生数据</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="width: 96%border-collapse: separatetext-align: center">
<tr>
<td colspan="3">
从Excel中导入</td>
</tr>
<tr>
<td colspan="3" style="text-align: leftheight: 9px">
</td>
</tr>
<tr>
<td align="center" style="width: 20%">
请选择Excel文件路径</td>
<td align="center" style="width: 483pxheight: 18pxtext-align: left">
<asp:FileUpload ID="FileUpload1" runat="server" Width="555px" /></td>
<td align="center" style="width: 10%">
<asp:Button ID="Btn_Inport" runat="server" Text="导 入" OnClick="Btn_Inport_Click" /></td>
</tr>
<tr>
<td align="center">
请选择表名</td>
<td align="center" style="width: 483pxheight: 18pxtext-align: left">
<asp:DropDownList ID="DDList_Sheet" runat="server"></asp:DropDownList></td>
<td align="center">
</td>
</tr>
<tr>
<td colspan="3">
<asp:GridView ID="GV_Excel" runat="server" Height="133px" Width="100%">
</asp:GridView>
</td>
</tr>
<tr>
<td style="height: 18px">
</td>
<td style="width: 483pxheight: 18px">
</td>
<td style="width: 243pxheight: 18px">
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
2. 后台代码:
using System
using System.Data
using System.Configuration
using System.Collections
using System.Web
using System.Web.Security
using System.Web.UI
using System.Web.UI.WebControls
using System.Web.UI.WebControls.WebParts
using System.Web.UI.HtmlControls
using System.Data.OleDb
using System.Data.SqlClient
public partial class StudentInforInport : System.Web.UI.Page
{
string strConn = System.Configuration.ConfigurationManager.AppSettings["strconn"].ToString().Trim()//链接SQL数据库
protected void Page_Load(object sender, EventArgs e)
{
}
/// <summary>
/// 查询EXCEL电子表格添加到DATASET
/// </summary>
/// <param name="filenameurl">服务器路径</param>
/// <param name="table">表名</param>
/// <param name="SheetName">Sheet表名</param>
/// <returns>读取的DataSet </returns>
public DataSet ExecleDs(string filenameurl, string table, string SheetName)
{
string strConn = "Provider=Microsoft.Jet.OleDb.4.0" + "data source=" + filenameurl + "Extended Properties='Excel 8.0'"
OleDbConnection conn = new OleDbConnection(strConn)
conn.Open()
DataSet ds = new DataSet()
OleDbDataAdapter odda = new OleDbDataAdapter("select * from [" + SheetName + "]", conn)
odda.Fill(ds, table)
return ds
}
protected void Btn_Inport_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == false) //HasFile用来检查FileUpload是否有指定文件
{
Response.Write("<script>alert('请您选择Excel文件')</script>")
return//当无文件时,返回
}
string IsXls = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower()//System.IO.Path.GetExtension获得文件的扩展名
if (IsXls != ".xls")
{
Response.Write("<script>alert('只可以选择Excel文件')</script>")
return//当选择的不是Excel文件时,返回
}
string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + FileUpload1.FileName// 获取Execle文件名 DateTime日期函数
string savePath = Server.MapPath(("~\\upfiles\\") + filename)//Server.MapPath 获得虚拟服务器相对路径
FileUpload1.SaveAs(savePath)//SaveAs 将上传的文件内容保存在服务器上
OperExcel Excel = new OperExcel()
ArrayList AL_ExcelSheet = new ArrayList()
AL_ExcelSheet = Excel.ExcelSheetName(savePath)
DDList_Sheet.Items.Clear()
for (int i = 0i <AL_ExcelSheet.Counti++)
{
DDList_Sheet.Items.Add( AL_ExcelSheet[i].ToString() )
}
SqlConnection cn = new SqlConnection(strConn)
cn.Open()
DataSet ds = ExecleDs(savePath, filename, DDList_Sheet.Items[0].ToString())//调用自定义方法得到数据
DataTable dt = ds.Tables[0]
if (dt.Rows.Count == 0)
{
Response.Write("<script>alert('Excel表为空表,无数据!')</script>")//当Excel表为空时,对用户进行提示
}
else
{
// 数据
GV_Excel.DataSource = dt
GV_Excel.DataBind()
Response.Write("<script>alert('Excle表导入成功!')location='default.aspx'</script>")
}
cn.Close()
}
}
注意:当导入的Excel文件中的内容很大时,将发生莫名的错误。因此导入的文件不能太大,一般少于5MB.
Excel文件,另存为Html格式,就知道了Response.ContentType 是告诉浏览器,服务器传递过来的内容是什么格式
这个值默认是text/html
这个要在所有的客户机上设置浏览器权限,比如IE的修改方法:
进入Internet属性=》安全=》自定义级别,把ActiveX控件和插件下的所有选项都改成启用
因为js是客户端的,所以服务器不可能控制
我一般是用服务器生成html格式的Excel,然后设置
Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader("Content-Disposition", "inlinefilename=abc.xls")
这样来下载excel,而且这样不用修改客户端的ie设置